<template>
	<!-- 顶部导航栏 -->
	<u-navbar title="订单查询" placeholder :autoBack="true" leftIconSize='35' bgColor='#d3832a' leftIconColor='#ffffff'
		titleStyle='color:#ffffff'></u-navbar>

	<view class="container">
		<!-- 顶部搜索栏 -->
		<view class="header-search">
			<view class="search">
				<input class="searchInput" v-model="scancode" type="text">
			</view>

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

			</view>

		</view>

		<!-- 数据详情 -->
		<view class="dataInfo">
			<view class="dataInfo__item">
				<text class="label">订单码:</text>{{dataInfo.orderCode}}
			</view>
			<view class="dataInfo__item">
				<text class="label">订单状态:</text>{{orderStateDictionaries[dataInfo.orderStatus] || ''}}
			</view>
			<view class="dataInfo__item">
				<text class="label">品牌:</text>
				<text>
					{{dataInfo.brand || ''}}
				</text>
			</view>
			<view class="dataInfo__item">
				<text class="label">商场名称:</text>
				<text>
					{{dataInfo.mallName || ''}}
				</text>
			</view>
			<view class="dataInfo__item">
				<text class="label">商场收货人:</text>
				<text>
					{{dataInfo.consigneePerson || ''}}
				</text>
			</view>
			<view class="dataInfo__item">
				<text class="label">商场电话:</text>
				<text>
					{{dataInfo.consigneeMobile || ''}}
				</text>
			</view>
			<view class="dataInfo__item">
				<text class="label">客户名称:</text>
				<text>
					{{dataInfo.customerName || ''}}
				</text>
			</view>
			<view class="dataInfo__item">
				<text class="label">客户电话:</text>
				<text>
					{{dataInfo.customerTelephone || ''}}
				</text>
			</view>
			<view class="dataInfo__item">
				<text class="label">发货日期:</text>
				<text>{{''}}</text>
			</view>
			<view class="dataInfo__item">
				<text class="label">齐套状态:</text>
				<text>
					{{dataInfo.completeSet === 1 ? '齐套' : '未齐套'}}
				</text>
			</view>
			<view class="dataInfo__item w100">
				<view class="label">收货地址:</view>
				<view>{{dataInfo.customerAddress || ''}}</view>
			</view>
		</view>

		<view class="orderInfo">
			<view class="title">
				<view @click="showArticleMadeToOrderModule" :class="{'active': showArticleMadeToOrder}">
					订制品(<text class="title__number">{{packageList.length}}</text>件)
				</view>
				<view @click="showArticleMadeToOrder = false" :class="{'active': !showArticleMadeToOrder}">
					库存品(<text class="title__number">{{stockList.length}}</text>件)
				</view>
			</view>

			<!-- 订制品 -->
			<view class="packagesList" v-if="packageList.length !== 0 && showArticleMadeToOrder">
				<view v-if="!isBatchOperation">
					<view class="batchOperationBtn" @click="batchOperationBtn">批量操作</view>
				</view>
				<view v-else style="display: flex;">
					<view class="batchOperationBtn" @click="handleCheckAll">全选</view>
					<view class="batchOperationBtn" @click="handleInvertSelection">反选</view>
					<view class="batchOperationBtn" @click="batchPrint">打印</view>
					<!-- <view class="batchOperationBtn" @click="handleMaterialReplenishment">物料补充</view> -->
				</view>

				<scroll-view scroll-y="true" style="height: 40vh; margin-top: 10px;">
					<uni-table type="selection" border stripe emptyText="暂无更多数据" @selection-change="selectionChange">
						<!-- 表头行 -->
						<uni-tr>
							<uni-th align="left">包条码</uni-th>
							<uni-th align="left">库位信息</uni-th>
							<uni-th align="left">托盘信息</uni-th>
							<uni-th align="left">三级品</uni-th>
							<!-- <uni-th align="center">数量</uni-th> -->
							<uni-th align="center">商场名称</uni-th>
							<uni-th align="center">是否签收</uni-th>
						</uni-tr>
						<!-- 表格数据行 -->
						<block v-for="item in packageList">
							<uni-tr>
								<!-- 包条码 -->
								<uni-td>{{item.orderPackageCode}}</uni-td>
								<!-- 库位信息 -->
								<uni-td>{{item.warehouse}}</uni-td>
								<!-- 托盘信息 -->
								<uni-td>{{item.trayName}}</uni-td>
								<!-- 三级品 -->
								<uni-td>{{item.thirdProduct}}</uni-td>
								<!-- <uni-td align="center">{{item.pallet}}</uni-td> -->
								<!-- 商场 -->
								<uni-td align="center">{{item.materialName}}</uni-td>
								<!-- 是否签收 -->
								<uni-td align="center">{{item.orderPackageStatus === '70' ? '已签' : '未签'}}</uni-td>
							</uni-tr>
						</block>

					</uni-table>
				</scroll-view>

				<!-- 				<u-checkbox-group v-model="checkboxValue" placement="column">
					<view :class="{'packagesList__item':true, 'active': item.orderPackageCode === scancode }"
						v-for="item in packageList" :key="item.orderPackageCode">
						<view>
							<u-checkbox :name="item.id" :checked="item.isChecked" @change="checkboxChange(item)" size="18px" />
						</view>
						<text>{{item.orderPackageCode}}</text>
						<text>{{item.warehouse}}</text>
						<text>{{item.thirdProduct}}</text>
						<text>{{item.pallet}}</text>
						<text>{{item.materialName}}</text>
						<text>{{item.orderPackageStatus === '70' ? '已签' : '未签'}}</text>
					</view>
				</u-checkbox-group> -->
			</view>

			<!-- 库存品 -->
			<view class="packagesList" v-else-if="stockList.length !== 0 && !showArticleMadeToOrder">
				<view class="packagesList__item" v-for="item in stockList" :key="item">
					<text>{{item.cargoNumber}}</text>
					<text>{{item.descriptionGoods}}</text>
					<text>{{item.marketName}}</text>
					<text>{{item.serviceNumber}}</text>
					<text>{{item.orderPackageStatus === '70' ? '已签' : '未签'}}</text>
				</view>
			</view>
		</view>
	</view>
	<tiplist ref="tiplists"></tiplist>
	<PopUp ref="MaterialReplenishment">
		<u--form labelPosition="left" label-width="80px" :model="form" ref="uForm">
			<u-form-item label="物料名称" borderBottom ref="item1">
				<u--input v-model="form.name" border="bottom"></u--input>
			</u-form-item>
			<u-form-item label="物料名称" borderBottom ref="item1">
				<u--input v-model="form.name" border="bottom"></u--input>
			</u-form-item>
			<u-form-item label="物料名称" borderBottom ref="item1">
				<u--input v-model="form.name" border="bottom"></u--input>
			</u-form-item>
			<u-form-item label="物料名称" borderBottom ref="item1">
				<u--input v-model="form.name" border="bottom"></u--input>
			</u-form-item>
		</u--form>
	</PopUp>
	<!-- #ifdef APP -->
	<saomiao2 :ishidestop="scanState !== 0"></saomiao2>
	<!-- #endif -->
	<BluetoothList ref="bluetoothList"></BluetoothList>
</template>

<script lang="ts" setup>
	import { ref, reactive, shallowRef, watch, nextTick } from 'vue';
	import {
		onShow,
		onHide,
		onLoad,
		onReachBottom,
		onPullDownRefresh
	} from '@dcloudio/uni-app'
	import utils from '@/utils/utils.js';
	import {
		distributionOrderInFuzzyQuery,
		distributionOrderInfoInQuery,
		BatchPrintPackages
	} from '@/api/user.js'
	import useBluetoothStore from '@/store/useBluetoothStore.js';
	import useSystemSettingsStore from '@/store/useSystemSettingsStore';
	import { storeToRefs } from 'pinia';
	const { scanState } = storeToRefs(useSystemSettingsStore())
	const bluetoothList = ref(null)
	const bluetoothStore = useBluetoothStore()
	const { bluetoothInfo } = storeToRefs(bluetoothStore)
	// type列表是否显示
	const isShowTypeList = ref<Boolean>(false)

	// 订单列表是否显示
	const isShowOrderList = ref<Boolean>(false)

	// 查询订单列表
	const distributionOrderList = shallowRef<string[]>([])

	// 订单详情
	const dataInfo = shallowRef<any>({})

	// 包件列表
	const packageList = ref([])

	// 被选中包件列表
	let checkboxValue = reactive([])

	// 是否开启批量操作
	const isBatchOperation = ref<Boolean>(false)

	// 是否显示订制品
	const showArticleMadeToOrder = ref<Boolean>(true)

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

	// 库存品列表
	const stockList = shallowRef([])

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

	// 订单状态字典
	const orderStateDictionaries = reactive({
		'10': '部分入库',
		'20': '已入库',
		'30': '部分出库',
		'40': '已出库',
		'50': '部分装车',
		'60': '已装车',
		'70': '部分签收',
		'80': '已签收',
	})

	// 顶部搜素表单
	const searchForm = reactive({
		condition: '',
		searchTypeList: [
			{
				label: '包件查询',
				type: 1
			},
			{
				label: '订单查询',
				type: 2
			},
		],
		type: 1,
	})

	/** 修改物料表单 */
	const form = ref({})

	// 组件实例
	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

				scandata()
			}
		})
		// #endif


	})

	// 关闭扫描监听
	// onHide(() => {
	// 	uni.$off('scancodedate')
	// })

	onPullDownRefresh(() => {
		const timer = setTimeout(() => {
			dataInfo.value = {}
			scancode.value = ''
			packageList.value = []

			uni.stopPullDownRefresh()
			clearTimeout(timer)
		}, 500)
	})

	async function scandata() {
		searchForm.condition = scancode.value
		// let res = await distributionOrderInFuzzyQuery(searchForm)
		const res = await distributionOrderInfoInQuery(searchForm)
		const { code, data } = res
		if (code === 200) {
			dataInfo.value = data
			packageList.value = data.list.map(item => {
				item.isChecked = false
				return item
			})
			stockList.value = data.stockList
		}
	}

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

	// 改变搜索表单内type
	function handleSearchFormType(type : number) {
		searchForm.type = type
		// 关闭type列表
		isShowTypeList.value = !isShowTypeList.value
	}

	// 是否显示type列表
	function showTypeList() {
		isShowTypeList.value = !isShowTypeList.value
	}

	// 选择订单
	async function handleSearchOrder(order : string) {
		scancode.value = order
		// 关闭搜索下拉框
		isShowOrderList.value = false
		// 清空订单列表数组
		distributionOrderList.value = []
		// 发送获取订单详情的请求
		const res = await distributionOrderInfoInQuery(searchForm)
		const { code, data } = res
		if (code === 200) {
			dataInfo.value = data
			packageList.value = data.list.map(item => {
				item.isChecked = false
				return item
			})
			stockList.value = data.stockList
		}
	}

	// 显示订制品模块
	function showArticleMadeToOrderModule() {
		showArticleMadeToOrder.value = true
		isBatchOperation.value = false
	}

	// 复选框
	const checkboxChange = (item) => {
		packageList.value.forEach(val => {
			if (val.id === item.id) val.isChecked = !val.isChecked
		})
		console.log(packageList.value)
	};

	// 开启批量操作
	function batchOperationBtn() {
		isBatchOperation.value = true
	}

	// 全选
	function handleCheckAll() {
		packageList.value.forEach(item => item.isChecked = true)
	}

	// 反选
	function handleInvertSelection() {
		packageList.value.forEach(item => item.isChecked = !item.isChecked)
	}

	// 批量打印
	async function batchPrint() {
		const idsArr = []
		packageList.value.forEach(item => {
			if (item.isChecked) idsArr.push(item.id)
		})
		const ids = idsArr.join(',')
		if (!ids) return uni.showToast({
			title: '最少选择一条数据',
			icon: 'none'
		})
		const res = await BatchPrintPackages(ids)
		const { code, data } = res
		if (code !== 200) return
		console.log('res :>> ', res);
		tiplists.value.setdetails({
			title: '请选择需要打印的包条码',
			isshow: true,
			tipstate: 2,
			list: [],
			inputtext: '',
			confirmTxt: '确认选择',
			isonecheck: true,
			success: () => {
				// if (deta.checklist.length == 0) {
				// 	uni.showToast({
				// 		title: '请选择包条码',
				// 		icon: 'none'
				// 	})
				// 	return
				// }
				console.log('data :>> ', data);
				// #ifdef APP
				if (!bluetoothInfo.value.name) return bluetoothList.value.setdetails({ isshow: true })
				let _isReturn = false
				data.map(item => {
					if (_isReturn) return
					let text = '! 0 200 200 330 1\r\n'
					text += 'SETBOLD 1\r\n'
					text += `T 56 0 0 0 ${item.orderCode}\r\n`
					text += 'LINE 0 50 420 50 3\r\n'
					text += `T 55 0 0 60 客户\r\n`
					text += 'LINE 40 50 40 110 3\r\n'
					text += `T 55 0 50 60 ${item.customerName}\r\n`
					text += 'LINE 40 80 420 80 3\r\n'
					text += `T 55 0 50 90 ${item.customerAddress}\r\n`
					text += 'LINE 0 110 420 110 3\r\n'
					text += `T 55 0 0 120 物料\r\n`
					text += 'LINE 40 110 40 140 3\r\n'
					text += `T 55 0 50 120 ${item.materialName || item.category}\r\n`
					text += 'LINE 0 140 420 140 3\r\n'
					text += 'B QR 150 150 M 2 U 4\r\n'
					text += `MA,${item.qrCode}\r\n`
					text += 'ENDQR\r\n'
					text += `T 55 0 140 260 ${item.qrCode}\r\n`
					text += 'FORM\r\n'
					text += 'PRINT\r\n'
					utils.getbl(bluetoothInfo.value, text).catch(() => {
						bluetoothList.value.setdetails({ isshow: true })
						_isReturn = true
					})
				})
				if (_isReturn) return
				// #endif
				tiplists.value.setdetails({ isshow: false })
			},
			cancel: (details) => {
				tiplists.value.setdetails({ isshow: false })
			},
			close: (details) => {
				tiplists.value.setdetails({ isshow: false })
			}
		})
	}

	/** 
	 * 物料补录
	 */
	const handleMaterialReplenishment = () => {
		const idsArr = []
		packageList.value.forEach(item => {
			if (item.isChecked) idsArr.push(item.id)
		})
	}
</script>

<style lang="scss" scoped>
	.w100 {
		width: 100%;
	}

	// 最外层容器
	.container {
		padding: 20upx;
		font-size: 28upx; // 本页字体大小
	}

	// 顶部搜索栏
	.header-search {
		height: 60upx;
		padding: 0 0 20upx;
		// border-bottom: 1upx solid #aaa;
		display: flex;
		justify-content: space-between;

	}

	.search {
		position: relative;

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

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

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

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

	.dataInfo__item {
		flex: none;
		min-width: 50%;
		line-height: 60upx;
		display: inline-flex;

		.label {
			display: inline-block;
			width: 160upx;
			text-align: right;
			margin-right: 20rpx;
		}
	}

	// 订单列表信息
	.orderInfo {
		background: #fff;
		margin-top: 10upx;

		// 头部统计
		.title {
			display: flex;
			justify-content: space-around;
			font-size: 32upx;
			font-weight: bold;
			margin-bottom: 20upx;

			&>view {
				padding: 15upx 0;
				flex: 1;
				text-align: center;
				position: relative;

				&::after {
					content: '';
					display: block;
					position: absolute;
					height: 4upx;
					width: 0;
					background: var(--subjectColor);
					top: 100%;
					left: 50%;
					transition: all 0.5s;
				}

				&.active::after {
					width: 100%;
					left: 0;
				}
			}
		}

		.title__number {
			color: var(--subjectColor);
		}

		// 批量操作按钮
		.batchOperationBtn {
			border: 1upx solid var(--subjectColor);
			text-align: center;
			padding: 10upx 0;
			color: var(--subjectColor);
			border-radius: 10upx;
			width: 200upx;
			font-size: 28upx;
			margin: 0;
			margin-right: 10upx;
		}

		.packagesList__item {
			display: grid;
			grid-template-columns: 1fr 3fr 1fr 1fr 3fr 1fr 1fr;
			// display: flex;
			margin: 10upx 0;

			&.active {
				background: #e40b2c;
				color: #fff;
			}
		}
	}

	.uni-table-scroll {
		zoom: 0.9;
	}

	.uni-table-td,
	.uni-table-th {
		--borderColor: #000;
		color: var(--borderColor);
		padding: 10upx;
	}

	.table--border {
		--borderColor: #000;
		border-color: var(--borderColor);
	}

	:deep(.checkbox.tr-table--border) {
		--borderColor: #000;
		border-color: #000;

		.checkbox__inner {
			border-color: #000;
		}
	}
</style>