<template slot-scope="scope">
	<view>
		<view class="sparepartList">
			<!-- <uni-nav-bar fixed="true" statusBar="true" left-icon="back" title="申请备品备件" @clickLeft="back">
				<view slot="right" @click="confirm">确定</view>
			</uni-nav-bar> -->
			<uni-nav-bar fixed="true" statusBar="true" left-icon="back" title="搜索" @clickLeft="back">
				<!--右菜单-->
				<template slot="right">
					<u-button type="success" size="small" class="u-reset-button" @click="openTreePicker" text="选择维度"></u-button>
				</template>
			</uni-nav-bar>
			<view class="searchBar">
				<u-icon class="icon" :size="50" name="list" @click="show = true"></u-icon>
				<u-search v-model="searchForm.assetName" shape="round" searchIconSize="50" :clearabled="true" :actionStyle="searchStyle" @search="search" @custom="search" @clear="search"></u-search>
			</view>
			<view class="listBox">
				<u-list v-if="tableData.length > 0" class="list" @scrolltolower="scrolltolower">
					<u-list-item v-for="(item, index) in tableData" :key="index">
						<u-cell value="内容">
							<view slot="title" class="u-slot-title">{{ item.name }}</view>
							<view slot="label" class="u-slot-title">{{ item.modelType }}/{{ item.specification }}</view>
							<view slot="value" class="u-cell-value">
								<u-checkbox-group size="30" iconPlacement="right" placement="column" @change="selectItem($event, index)">
									<u-checkbox size="30" :labelSize="30" :customStyle="{ marginBottom: '8px' }" :key="index" :label="item.availableCountBase" :name="item"></u-checkbox>
								</u-checkbox-group>
							</view>
						</u-cell>
					</u-list-item>
				</u-list>
				<view v-else class="no-data">暂无数据</view>
			</view>
			<!-- <u-picker v-if="show" :show="show" :columns="columns" keyName="label" @cancel="close" @confirm="confirm" :defaultIndex="dimensionIndex"></u-picker> -->
			<ba-tree-picker ref="treePicker" key="verify" :multiple="false" @select-change="confirm" title="选择维度" :localdata="columns" valueKey="id" textKey="name" childrenKey="children" />
		</view>
	</view>
</template>
<script>
	import { getDetailById, getBatchDetails, applySpareParts, saveNew, getInventoryDetails, getMaterielDetails } from '@/api/repair'
	export default {
		data() {
			return {
				checkboxList: [],
				tableData: [],
				dimensionIndex: [0],
				dimension: 4,
				show: false,
				// columns: [
				// 	[
				// 		{
				// 			label: '物料维度',
				// 			value: '4'
				// 		},
				// 		{
				// 			label: '包装维度',
				// 			value: '3'
				// 		},
				// 		{
				// 			label: '批次维度',
				// 			value: '2'
				// 		}
				// 	]
				// ],
				columns: [
					{
						name: '物料维度',
						id: '4'
					},
					{
						name: '包装维度',
						id: '3'
					},
					{
						name: '批次维度',
						id: '2'
					}
				],
				searchForm: {
					assetName: ''
				},
				searchStyle: {
					background: '#F62F33',
					width: '105rpx',
					height: '50rpx',
					borderRadius: '30rpx',
					fontSize: '28rpx',
					color: '#FFFFFF',
					lineHeight: '50rpx',
					textAlign: 'center'
				},
				pageNum: 1,
				warehousingMaterialList: [],
				batchDetailsVOList: [],
				materialCodeReqList: [],
				selectionList: [],
				wlParams: {},
				materialObj: {},
				total: 0
			}
		},
		onLoad(options) {
			this.id = options.id
		},
		onShow() {
			this.getList()
		},
		methods: {
			openTreePicker() {
				this.$refs.treePicker._show()
			},
			search() {
				this.pageNum = 1
				this.tableData = []
				this.getList()
			},
			getList() {
				uni.showLoading({
					title: '加载中'
				})
				return new Promise(async (resolve, reject) => {
					try {
						let params = { assetName: this.searchForm.assetName, dimension: this.dimension, pageNum: this.pageNum, size: 15, categoryLevelId: 6 }
						if (this.dimension == 2) {
							let res = await getBatchDetails(params)
							this.total = res.count
							this.tableData = this.tableData.concat(
								res.list.map(item => {
									return {
										...item,
										minUnit: item.packingUnit,
										oid: item.stockBatchId,
										assetCode: item.code
									}
								})
							)
						} else if (this.dimension == 3) {
							let res = await getInventoryDetails(params)
							this.total = res.count
							this.tableData = this.tableData.concat(
								res.list.map(item => {
									return {
										...item,
										batchNo: item.batchNum,
										minUnit: item.packingUnit,
										packingCountBase: 1,
										oid: item.id,
										assetCode: item.code
									}
								})
							)
						} else if (this.dimension == 4) {
							let res = await getMaterielDetails(params)
							this.total = res.count
							this.tableData = this.tableData.concat(
								res.list.map((item, index) => {
									return {
										...item,
										availableCountBase: 1,
										packingCountBase: 1,
										minUnit: item.packingUnit,
										oid: item.id + this.pages.pageNum + (index + 1)
									}
								})
							)
						}
						uni.hideLoading()
						resolve()
					} catch (error) {
						console.log(error)
						uni.hideLoading()
						reject()
					}
				})
			},
			selectItem(data, index) {
				if (data[0]) {
					this.checkboxList[index] = data[0]
				} else {
					this.checkboxList[index] = ''
				}
			},
			confirm(data) {
				console.log(data)
				this.dimension = data.value[0].value
				this.dimensionIndex = data.indexs
				this.show = false
				this.pageNum = 1
				this.tableData = []
				this.getList()
			},
			close() {
				this.show = false
			},
			scrolltolower(e) {
				console.log(e)
			},
			back() {
				uni.navigateBack({
					delta: 1
				})
			},
			async handleExit(arr) {
				console.log(arr)
				let ids = null
				let batchIds = null
				let materielIds = null
				if (this.dimension == 3) {
					ids = arr.map(item => {
						return item.id
					})
				} else if (this.dimension == 2) {
					ids = arr.map(item => {
						return item.recordId
					})
					batchIds = arr.map(item => {
						return item.stockBatchId
					})
				} else if (this.dimension == 4) {
					materielIds = arr.map(item => {
						return item.materielId
					})
					ids = arr.map(item => {
						return item.recordId
					})
				} else {
					ids = arr.map(item => {
						return item.recordId
					})
				}
				let categoryIds = arr.map(item => {
					return item.id
				})
				let batchNos = arr.map(item => {
					return item.batchNo
				})
				let outInDetailIds = arr.map(item => {
					return item.outInDetailId
				})
				const parmas = {
					categoryLevelId: 6,
					type: this.dimension,
					categoryIds,
					batchNos,
					batchIds,
					ids,
					outInDetailIds,
					materielIds
				}
				const data = await getDetailById(parmas)
				return data
			},
			async confirm() {
				let checkboxList = this.checkboxList.filter(item => !!item)
				if (!checkboxList.length) {
					uni.showToast({
						icon: 'error',
						title: '请选择备品备件！',
						duration: 2000
					})
					return
				}
				const data = await this.handleExit(checkboxList)
				let arr = []
				if (this.dimension == 4) {
					arr = checkboxList.map(item => {
						return { ...item, assetName: item.name }
					})
				}
				this.detailData({ ...data, wlList: arr }, this.dimension)
			},

			detailData(data, dimension) {
				this.dimension = dimension
				console.log('总数居', data)
				console.log(dimension)
				// this.onSelectTableDataVal = data.realTimeInventoryVOList;
				this.warehousingMaterialList = data.realTimeInventoryVOList.map(next => {
					delete next.updateTime
					delete next.createTime
					return {
						...next,
						realInventoryAmount: 0,
						assetType: 6,
						outInNum: '',
						assetCode: next.code,
						assetName: next.name,
						bizStatus: 2,
						contactCode: next.contactCode
					}
				})
				// this.batchDetailsVOList = data.batchDetailsVOList;

				if (dimension == 4) {
					this.materialCodeReqList = data.wlList
					this.selectionList = data.wlList

					let params = {
						realTimeInventoryNewPOList: data.realTimeInventoryVOList
					}

					for (const item of params.realTimeInventoryNewPOList) {
						item.inventoryDetailsNewPOList = item.inventoryDetailsVOList

						for (const detail of item.inventoryDetailsNewPOList) {
							detail.outInMaterialDetailsAddPOList = []

							for (const wlItem of data.wlList) {
								if (detail.id === wlItem.recordId) {
									detail.outInMaterialDetailsAddPOList.push({
										...wlItem
									})
								}
							}
						}
					}
					this.wlParams = params
					this.materialObj = data
				} else if (dimension == 3) {
					//包装维度出库
					const list = data.realTimeInventoryVOList
					//获取包装维度
					let packArr = []
					for (const item of list) {
						if (item.inventoryDetailsVOList.length != 0) {
							for (const iterator of item.inventoryDetailsVOList) {
								packArr.push({ ...iterator, batchNo: iterator.batchNum })
							}
						}
					}
					this.batchDetailsVOList = packArr.map(item => {
						return {
							...item,
							packingCountBase: dimension == 4 || dimension == 3 ? 1 : item.packingCountBase
							// weight: 0
						}
					})
					//物料维度数据
					let meteArr = []
					for (const item of packArr) {
						if (item.materialDetailsVOList.length != 0) {
							for (const iterator of item.materialDetailsVOList) {
								meteArr.push({
									...iterator
								})
							}
						}
					}
					this.materialCodeReqList = meteArr
					//再次打开选择上
					this.selectionList = list
					//send数据
					this.wlParams = { realTimeInventoryNewPOList: list }
					this.wlParams.realTimeInventoryNewPOList.forEach(item => {
						item.inventoryDetailsNewPOList = item.inventoryDetailsVOList
						item.inventoryDetailsNewPOList.forEach(ite => {
							// ite.weight = 0;
							ite.outInMaterialDetailsAddPOList = ite.materialDetailsVOList
						})
					})
				} else {
					//   else if (dimension == 2) {
					//   this.batchDetailsVOList = data.wlList;
					//   this.selectionList = data.wlList;
					// }
					//物品维度出库
					const list = data.realTimeInventoryVOList
					//获取包装维度
					let packArr = []
					for (const item of list) {
						if (item.inventoryDetailsVOList.length != 0) {
							for (const iterator of item.inventoryDetailsVOList) {
								packArr.push({ ...iterator, batchNo: iterator.batchNum })
							}
						}
					}
					this.batchDetailsVOList = packArr.map(item => {
						return {
							...item,
							packingCountBase: dimension == 3 ? 1 : item.packingCountBase
							// weight: 0
						}
					})
					//物料维度数据
					let meteArr = []
					for (const item of packArr) {
						if (item.materialDetailsVOList.length != 0) {
							for (const iterator of item.materialDetailsVOList) {
								meteArr.push({
									...iterator
								})
							}
						}
					}
					this.materialCodeReqList = meteArr
					//再次打开选择上
					this.selectionList = list
					//send数据
					this.wlParams = { realTimeInventoryNewPOList: list }
					this.wlParams.realTimeInventoryNewPOList.forEach(item => {
						item.inventoryDetailsNewPOList = item.inventoryDetailsVOList
						item.inventoryDetailsNewPOList.forEach(ite => {
							// ite.weight = 0;
							ite.outInMaterialDetailsAddPOList = ite.materialDetailsVOList
						})
					})
				}
				this.handleNewSave()
			},
			async handleNewSave() {
				let userInfo = wx.getStorageSync('userInfo')
				let obj = {
					fromUser: userInfo.userId,
					bizType: '4', // 领用出库
					extInfo: {
						assetType: 6,
						verifyDeptCode: userInfo.deptId[0],
						verifyDeptName: userInfo.deptName
					},
					type: 2,
					fromType: 2
				}
				obj = { ...obj, ...this.wlParams }
				if (this.dimension == 4) {
					obj.num = this.materialObj.wlList.length
				} else {
					obj.num = this.materialCodeReqList.length
				}
				obj.storageSource = 1
				try {
					const res = await saveNew(obj)
					if (res.code == 0) {
						let arr = obj.realTimeInventoryNewPOList.map(item => {
							return {
								sparePartsId: item.id,
								sparePartsList: JSON.stringify({
									...item,
									inventoryDetailsNewPOList: [],
									inventoryDetailsVOList: [],
									outInIds: res.data
								})
							}
						})
						applySpareParts({
							workOrderId: this.id,
							infoList: arr
						}).then(res => {
							uni.showToast({
								icon: 'success',
								title: '申请成功！',
								duration: 2000
							})
							setTimeout(() => {
								this.back()
							}, 1000)
						})
					}
				} catch (error) {
					console.log(error)
				}
			},
			// 触底加载
			scrolltolower() {
				this.loadmore()
			},
			loadmore() {
				if (this.tableData.length < this.total) {
					this.pageNum += 1
					this.getList()
				}
			}
		}
	}
</script>
<style lang="scss" scoped>
	.sparepartList {
		height: 100vh;
		width: 100%;
		overflow: hidden;
		display: flex;
		flex-direction: column;
		.searchBar {
			padding: 20rpx;
			display: flex;
			.icon {
				margin-right: 20rpx;
			}
		}
		.listBox {
			flex: 1;
			height: 0;
			.list {
				height: 100% !important;
			}
			.u-cell-value {
				width: 70rpx;
			}
			.no-data {
				height: 100%;
				width: 100%;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 30rpx;
			}
		}
	}
</style>
