<template>
	<view style="margin: 10rpx;">
		<u-navbar back-text="返回" title="立体库出库" :background="background"></u-navbar>
		<u-form ref="testForm" labelWidth="200" style="padding-bottom: 200rpx;">
			<u-form-item class="item2">
				<p>物料:</p>
				<u-input v-model="materialSpecName" border @input="getSdkInfo"></u-input>
			</u-form-item>
			<u-form-item class="item2">
				<p>SDK规格:</p>
				<zxzUniDataSelect @change="getMATERIALSPECNAME" filterable v-model="sdk_id" :localdata="sdkList">
				</zxzUniDataSelect>
			</u-form-item>
			<u-form-item class="item2">
				<p>库区:</p>
				<zxzUniDataSelect @change="changeSlect" filterable v-model="AreaName" :localdata="Area">
				</zxzUniDataSelect>
			</u-form-item>
			<u-form-item>
				<p>出货口:</p>
				<zxzUniDataSelect filterable v-model="outPort" :localdata="outPortList">
				</zxzUniDataSelect>
			</u-form-item>
			<br />
			<checkbox-group @change="IFHaveBh">
				<label>
					<checkbox value="bh" />是否已备货
				</label>
			</checkbox-group>
			<br />

			<u-card style="border: 1rpx solid #0081ff" :show-head="false" :full="true"
				:body-style="{ height: '100rpx' }">
				<view slot="body">
					<u-row>
						<u-col span="6">
							<view>累计选择支数：{{ sumJs || '0' }}</view>
						</u-col>
						<u-col span="6">
							<view>累计选择数量：{{ sumQuantity || '0' }}</view>
						</u-col>
					</u-row>
				</view>
			</u-card>

			<!-- 分栏器 -->
			<view class="uni-padding-wrap uni-common-mt">
				<uni-segmented-control :current="current" :values="items" :style-type="styleType"
					:active-color="activeColor" @clickItem="clickitem" />
			</view>
			<view>
				<view v-show="current === 0">

					<view class="pagination">
						<u-button size="mini" @click="prevPage" :disabled="currentPage === 1">上一页</u-button>
						<span v-for="page in displayedPages" :key="page">
							<u-button size="mini" @click="goToPage(page)" :class="{ active: currentPage === page }">
								{{ page }}
							</u-button>
						</span>
						<u-button size="mini" @click="nextPage" :disabled="currentPage === totalPages">下一页</u-button>
					</view>

					<view class="search-box">
						<u-input type="text" placeholder="请输入搜索料号" v-model="searchSpec" class="search-input"
							clearable />
					</view>
					<view class="container" style="margin-bottom: 80px;">
						<view id="list-item" v-for="(item, index) in paginatedlist_detail" :key="item.id"
							class="selectable-view" @click="toggleSelection(item)"
							:class="{ 'selected': isSelected(item), 'hidded' : isHidded(item) }">
							<view>
								<view>
									<!-- <div>
										<text class="card-description"> 序号: {{list_detail.length -  index}}</text>
									</div> -->
									<div>
										<text class="card-description"> 批次: {{ item.CHARGE }}</text>
									</div>
									<div>
										<text class="card-description"> 料号: {{ item.MATERIALSPECNAME }} 阶段:
											{{ item.PHASE }} SDK规格: {{ item.SPECNAME }}</text>
									</div>
									<div>
										<text class="card-description"> 品名: {{ item.DESC_CN }}</text>
									</div>
									<div>
										<text class="card-description"> 实际规格: {{ item.TRUEGG }}</text>
									</div>
									<div>
										<text class="card-description"> 仓库: {{ item.ERPLOCATION }}</text>
									</div>
									<div>
										<text class="card-description"> 货位: {{ item.LOCATIONNAME }}</text>
									</div>
									<div>
										<text class="card-description"> 数量: {{ item.MATERIALQUANTITY }}
											{{ item.UNIT }}</text>
									</div>
									<div>
										<text class="card-description"> 载具: {{ item.TRAYNAME }} 库区:
											{{ item.DESCRIPTION }}</text>
									</div>
									<div>
										<text class="card-description"> 立库货架: {{ item.SHELFNAME }} </text>
									</div>
									<div>
										<text class="card-description"> 宽幅: {{ item.WIDTH }} 直径: {{ item.DIAMETER }}
										</text>
									</div>
									<div>
										<text class="card-description"> 偏移量: {{ item.DEVIATION }} 重量: {{ item.WEIGHT }}
										</text>
									</div>
									<div>
										<text class="card-description"> 生产线: {{ item.PRODUCTLINE }} </text>
									</div>

								</view>
							</view>
						</view>
					</view>
					<br />
				</view>
				<view v-show="current === 1">
					<view>
						<!-- 选中的项目: {{ selectedItems.map(i => list_detail[i].CHARGE).join(', ') }}  -->
						<view id="list-item" v-for="(item, index) in stockChoose" :key="item.id" class="selectable-view"
							@click="toggleSelection(item)" :class="{ 'selected': isSelected(index) }">
							<view>
								<view>
									<!-- <div>
										<text class="card-description"> 序号: {{list_detail.length -  index}}</text>
									</div> -->
									<div>
										<text class="card-description"> 批次: {{ item.CHARGE }}</text>
									</div>
									<div>
										<text class="card-description"> 料号: {{ item.MATERIALSPECNAME }} 阶段:
											{{ item.PHASE }} SDK规格: {{ item.SPECNAME }}</text>
									</div>
									<div>
										<text class="card-description"> 品名: {{ item.DESC_CN }}</text>
									</div>
									<div>
										<text class="card-description"> 实际规格: {{ item.TRUEGG }}</text>
									</div>
									<div>
										<text class="card-description"> 仓库: {{ item.ERPLOCATION }}</text>
									</div>
									<div>
										<text class="card-description"> 货位: {{ item.LOCATIONNAME }}</text>
									</div>
									<div>
										<text class="card-description"> 数量: {{ item.MATERIALQUANTITY }}
											{{ item.UNIT }}</text>
									</div>
									<div>
										<text class="card-description"> 载具: {{ item.TRAYNAME }} 库区:
											{{ item.DESCRIPTION }}</text>
									</div>
									<div>
										<text class="card-description"> 立库货架: {{ item.SHELFNAME }} </text>
									</div>
									<div>
										<text class="card-description"> 宽幅: {{ item.WIDTH }} 直径: {{ item.DIAMETER }}
										</text>
									</div>
									<div>
										<text class="card-description"> 偏移量: {{ item.DEVIATION }} 重量: {{ item.WEIGHT }}
										</text>
									</div>
									<div>
										<text class="card-description"> 生产线: {{ item.PRODUCTLINE }} </text>
									</div>

								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<checkbox-group @change="IFUserAGV">
				<label>
					<checkbox value="cb" />是否使用AGV
				</label>
			</checkbox-group>
			<br />
			<u-form-item label="起始点" v-if="AGVshow">
				<zxzUniDataSelect filterable v-model="INITILATION" :localdata="items_In"></zxzUniDataSelect>
			</u-form-item>
			<u-form-item label="目的点" v-if="AGVshow">
				<zxzUniDataSelect filterable v-model="ENDING" :localdata="items_En"></zxzUniDataSelect>
			</u-form-item>
			<u-form-item label="A/B轴" v-if="AGVshow">
				<zxzUniDataSelect filterable v-model="AB" :localdata="ABS"></zxzUniDataSelect>
			</u-form-item>
		</u-form>
		<view class="tabbar_bottom">
			<uni-datetime-picker style="align-items: center;" type="date" :clear-icon="false" v-model="commitDate"
				@maskClick="maskClick" />
			<u-button @click="FGStockIn" type="primary" :loading="loading">确定</u-button>
		</view>
	</view>
</template>

<script>
	import zxzUniDataSelect from "@/components/zxz-uni-data-select/zxz-uni-data-select.vue"
	export default {
		components: {
			zxzUniDataSelect
		},
		data() {
			return {
				sdkList: [],
				sdkListAll: [],
				sdk_id:'',
				commitDate: '',
				AREANAME: "",
				IFBh: "",
				outPort: "", // 出货口
				list_detail: [],
				items_In: [],
				items_En: [],
				INITILATION: '', //起始点
				ENDING: '', //目的地
				AB: '', //AB轴
				DURABLENAMECode: '', //卷芯
				AreaName: '',
				materialSpecName: '',
				Area: [],
				value: '',
				show: false,
				AGVshow: false,
				datamodel: '',
				tabH: 800, //表格的宽度
				RECEIVEACTNO: '', //入库单号
				background: {
					backgroundImage: 'linear-gradient(45deg, rgb(28, 187, 180), rgb(141, 198, 63))'
				}, //返回按钮的样式
				colors: ['#007aff', '#4cd964', '#dd524d'],
				styleType: 'button',
				BoxListInfo: [], //后端传回来的绑定表格的数据
				activeColor: '#007aff',
				loading: false,
				siteName: "",
				userId: "",
				items: [],
				stockChoose: [],
				outPortList: [],
				ABS: [{
						text: "A轴",
						value: "A"
					},
					{
						text: "B轴",
						value: "B"
					}
				],
				currentPage: 1, // 当前页码
				perPage: 10, // 每页显示的项目数  
				pageRange: 1, //前后显示的页码数量 
				isFolded: [], // 用于存储每个项目的折叠状态，初始为 false（不折叠）
				searchSpec: '', //搜索料号

				// 分栏器
				current: 0,
				items: ['库存列表', '备货列表'],
				styleType: 'text',
				activeColor: '#007aff',
			}
		},
		mounted() {
			this.GetArea()
			this.tabH = this.$GetRemainingHeight(4, 0); //定义表格的高度
			let that = this
			uni.getStorage({
				key: "sitename",
				success(res) {
					that.siteName = res.data
				}
			})
			uni.getStorage({
				key: "userid",
				success(res) {
					that.userId = res.data
				}
			})
			
			this.GetLiberaryBaeIn()
			this.GetLiberaryBaeEn()
			this.getTimeData();

		},
		computed: {
			displayedPages() {
				let start = Math.max(this.currentPage - this.pageRange, 1);
				let end = Math.min(this.currentPage + this.pageRange, this.totalPages);
				let pages = [];
				for (let i = start; i <= end; i++) {
					pages.push(i);
				}
				// 如果第一页不在范围内，添加省略号  
				if (start > 1) {
					pages.unshift('...');
				}
				// 如果最后一页不在范围内，添加省略号  
				if (end < this.totalPages) {
					pages.push('...');
				}
				return pages;
			},
			paginatedlist_detail() {
				const start = (this.currentPage - 1) * this.perPage;
				const end = start + this.perPage;
				return this.list_detail.slice(start, end);
			},
			totalPages() {
				return Math.ceil(this.list_detail.length / this.perPage);
			},

			sumJs() {
				// 计算累计选择支数  
				return this.stockChoose.reduce((total, item) => total + 1, 0);
			},
			sumQuantity() {
				// 计算累计选择数量  
				return this.stockChoose.reduce((total, item) => total + item.MATERIALQUANTITY, 0);
			},
		},
		methods: {
			getMATERIALSPECNAME() {
			  if(!this.materialSpecName){
			    this.$showMessage("请输入物料！")
			    return;
			  }
			},
			getSdkInfo() {
				this.sdkList = []
				this.$MyRequest('/label/getSDKSPEC', {
					materialSpecName: this.materialSpecName
				}).then((res) => {
					// this.sdkListAll = res.resultObj;
					// this.locatioNFilter('1')
					this.sdkList = res.data.resultObj;
				})
			},
			// locatioNFilter(query) {
			//     console.log(query)
			//   let arr = this.sdkListAll.filter((item) => {
			//     return (item.text.includes(query) || item.value.includes(query))
			//   })
			//   if (arr.length > 50) {
			//     this.sdkList = arr.slice(0, 50)
			//   } else {
			//     this.sdkList = arr
			//   }
			// },
			clickitem(e) {
				if (this.current !== e.currentIndex) {
					this.current = e.currentIndex //获取当前选中的index
				}
			},
			/* 分页方法 */
			prevPage() {
				if (this.currentPage > 1) {
					this.currentPage--;
				}
			},
			nextPage() {
				if (this.currentPage < this.totalPages) {
					this.currentPage++;
				}
			},
			goToPage(page) {
				if (page != "...") {
					this.currentPage = page;
				}

			},
			/* 分页方法 */
			getTimeData() {
				var year = new Date().getFullYear(); //年
				if (year < 1900) year = year + 1900;
				var month = new Date().getMonth() + 1; //月
				if (month < 10) month = '0' + month;
				var day = new Date().getDate(); //日
				if (day < 10) day = '0' + day;
				const calendar1 = year + '-' + month + '-' + day
				this.commitDate = calendar1
			},
			maskClick(e) {
				console.log('maskClick事件:', e);
			},
			outPortFn() {
				this.$MyRequest('/MaturationLibrary/getPort', {
					AREANAME: this.AREANAME
				}).then((res) => {
					let list = res.data.resultObj.map(item => {
						return {
							value: item.PORTNO,
							text: item.PORTNAME
						}
					})
					console.log(list)
					this.outPortList = list
				})
			},
			changeSlect(e) {
				this.outPort = "";
				this.list_detail = []
				this.stockChoose = []
				console.log('1', e)
				this.AREANAME = e.value
				this.outPortFn()
				this.getDetailQuery({
					AREANAME: this.AREANAME,
					SHIPREQUESTNAME: this.IFBh,
					MATERIALSPECNAME: this.materialSpecName,
					SDK_ID: this.sdk_id
				})
			},
			IFHaveBh(e) {
				let value = e.detail.value[0] || ""
				console.log(value)
				this.IFBh = value
				this.list_detail = []
				this.stockChoose = []
				this.getDetailQuery({
					AREANAME: this.AREANAME,
					SHIPREQUESTNAME: this.IFBh,
					MATERIALSPECNAME: this.materialSpecName,
					SDK_ID: this.sdk_id
				})
			},
			getDetailQuery(data) {
				this.loading = true
				this.$MyRequest('/MaturationLibrary/getPreStockOutByAuto', data).then((res) => {
					this.list_detail = res.data.resultObj
					this.loading = false
				})
			},
			toggleAllSelection(e, data) {
				console.log('调用了', data)
				this.stockChoose = data
			},
			//选择备货
			stockSelectionChange(e, selection) {
				console.log('调用了', selection)
				this.stockChoose = selection
			},

			toggleSelection(item) {
				const isSelected = this.isSelected(item);
				if (isSelected) {
					// 如果已选中，则移除该项目对象  
					this.stockChoose = this.stockChoose.filter(selectedItem => selectedItem !== item);
				} else {
					// 如果未选中，则添加该项目对象  
					this.stockChoose.push(item);
				}
			},
			isSelected(item) {
				// 检查项目对象是否在已选中的项目数组中  
				return this.stockChoose.includes(item);
			},

			isHidded(item) {
				// 检查项目对象是否在已选中的项目数组中  
				return item.MATERIALSPECNAME && !item.MATERIALSPECNAME.includes(this.searchSpec);
			},


			GetArea() {
				this.$MyRequest('/api/storage/getArea2', {}).then(res => {
					if (res.data.success) {
						console.log(res.data.resultObj)
						this.Area = res.data.resultObj
					} else {
						this.$showMessage(res.data.message)
					}
				}).catch(err => {
					this.$showMessage(err)
				})
			},
			confirm(e) {
				console.log(e[0].value)
				this.AreaName = e[0].value
			},
			IFUserAGV(e) {
				let value = e.detail.value[0]
				console.log(value)
				if (value == 'cb') {
					this.AGVshow = true
				} else {
					this.AGVshow = false
				}
			},
			GetLiberaryBaeIn() {
				//发送请求
				this.$MyRequest('/api/ApiQuery', {
					queryId: "GetLibraryBaseIn",
					version: "00001",
					params: {}
				}).then(res => {
					for (let i = 0; i < res.data.data.length; i++) {
						var _Arr = res.data.data[i];
						this.items_In.push({
							text: _Arr.LABEL,
							value: _Arr.VALUE
						});
					}
				}).catch(err => {
					this.$showMessage(err)
				})
			},
			GetLiberaryBaeEn() {
				//发送请求
				this.$MyRequest('/api/ApiQuery', {
					queryId: "GetLibraryBaseIn",
					version: "00002",
					params: {}
				}).then(res => {
					for (let i = 0; i < res.data.data.length; i++) {
						var _Arr = res.data.data[i];
						this.items_En.push({
							text: _Arr.LABEL,
							value: _Arr.VALUE
						});
					}
				}).catch(err => {
					this.$showMessage(err)
				})
			},
			/**
			 * 入库审核
			 */
			FGStockIn() {
				console.log(this.commitDate)
				if (this.stockChoose.length > 0) {
					this.loading = true;
					let ISAGV = this.AGVshow ? "TRUE" : "FALSE"
					let MATERIALPACKINGNAMELIST = this.stockChoose.map(item => {
						item.AREANAME = this.AREANAME
						item.FLAG = "OUT"
						item.OUTDESTINATION = this.AREANAME
						item.ISAGV = ISAGV
						item.INITILATION = this.INITILATION
						item.ENDING = this.ENDING
						item.AB = this.AB
						item.TRANSPORTCOMMANDTYPE = "OUT"
						item.PORT = this.outPort
						item.DURABLENAME = item.TRAYNAME
						// item.WIDTH = ""
						// item.DIAMETER = ""
						// item.DEVIATION = ""
						// item.WEIGHT = ""
						// item.PRODUCTLINE = ""
						// item.SHIPREOUESTNAME = ""

						return item;
					})
					this.$MyRequest('/MaturationLibrary/AutoStockOut', {
						SITENAME: "SDK",
						userId: this.userId,
						AREANAME: this.AREANAME,
						aimAreaName: "",
						outProt: '',
						erpLocation: "",
						erpFactory: "",
						locationName: "",
						barCode: "",
						// durableName:"102238",
						shipRequestName: "",
						commitDate: this.commitDate,
						MATERIALPACKINGNAME: MATERIALPACKINGNAMELIST
					}).then(res => {
						if (res.data.success) {
							this.loading = false;
							this.resetValue();
							this.$showMessage(res.data.message)
							this.list_detail = [];
						} else {
							this.loading = false;
							this.$showMessage(res.data.message)
							this.list_detail = [];
						}
					}).catch(err => {
						this.loading = false;
						this.$showMessage(err)
					});
				} else {
					this.$showMessage("请选择出库列表！")
				}
			},

			resetValue() {
				this.BoxListInfo = [];
				this.RECEIVEACTNO = "";
			},


		}
	}
</script>
<style>
	.btn-bottom {
		position: fixed;
		bottom: 0;
		width: 100%;
		left: 0;
	}
</style>
<style lang="scss">
	#list-item {

		margin-top: 16px;
		/* 卡片之间的间距 */
		// padding: 12px;
		/* 卡片内部的内边距 */
		background-color: #aaaa7f;
		/* 卡片背景色 */
		border-radius: 8px;
		/* 卡片边框圆角 */
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		/* 卡片阴影效果 */
	}

	.selectable-view {
		padding: 10px;
		margin: 5px;
		border: 1px solid #ccc;
		display: flex;
		align-items: center;
		cursor: pointer;
	}

	.selected {
		background-color: #007aff;
		color: white;
	}

	.hidded {
		display: none;
	}

	.pagination {
		display: flex;
		justify-content: center;
		margin-top: 20px;
	}

	.pagination button {
		margin: 0 5px;
		padding: 5px 10px;
	}

	.pagination button.active {
		font-weight: bold;
		color: red;
		/* 或者其他突出显示的颜色 */
	}

	.button-group button {
		display: inline-block;
		/* 使按钮以内联块级元素显示 */
		margin: 0 5px;
		/* 为按钮添加一些左右外边距 */
		/* 根据需要添加其他样式 */
	}
</style>