<template slot-scope="scope">
	<view class="content-box">
		<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="top-wrapper">
			<view class="searchBox rx-bc">
				<input v-model="assetName" placeholder="请输入物品名称" class="searchInput" />

				<view class="rx-sc">
					<image class="menu_icon" src="~@/static/pda/menu.svg" @click="handleSearch"></image>
					<u-button @click="search" type="success" size="small" class="u-reset-button" text="搜索"></u-button>
				</view>
			</view>
		</view>
		<view class="list_box">
			<u-list @scrolltolower="scrolltolower">
				<checkbox-group v-for="(item, index) in tableData" :key="index" @change="e => selectVal(e, item, index)">
					<label class="listBox rx-bs">
						<view class="listBox-sel">
							<checkbox :value="item.code" color="#fff" :disabled="item.disabled" :checked="item.checked" />
						</view>

						<view class="listBox-con">
							<view class="listBox-top rx-bc">
								<view>{{ item.name }}</view>
							</view>

							<view class="listBox-bottom rx">
								<view class="items">
									<text>编码</text>
									{{ item.code }}
								</view>

								<view class="items">
									<text>物料代号</text>
									{{ item.materielCode }}
								</view>

								<view class="items">
									<text>客户代号</text>
									{{ item.clientCode }}
								</view>

								<view class="items">
									<text>质检状态</text>
									{{ stateList[Number(item.runStatus)] }}
								</view>

								<view class="items">
									<text>包装库存</text>
									{{ item.packingCountBase }} {{ item.minUnit }}
								</view>

								<view class="items">
									<text>计量库存数量</text>
									{{ item.availableCountBase }} {{ item.measuringUnit }}
								</view>
							</view>
						</view>
					</label>
				</checkbox-group>

				<view v-if="tableData.length == 0" style="margin-top: 20vh">
					<u-empty iconSize="150" textSize="32" text="暂无数据"></u-empty>
				</view>
			</u-list>
		</view>

		<view class="bottom-wrapper rx-bc">
			<view>
				<checkbox v-if="!seletedAll" color="#fff" :checked="seletedAll" @tap="_seletedAll">全选</checkbox>
				<checkbox class="select-all" color="#fff" v-else :checked="seletedAll" @tap="_seletedAll">取消全选</checkbox>
			</view>
			<view>
				<u-button type="success" size="small" class="u-reset-button" :disabled="!checkListLen" @click="config">
					<view>选择( {{ checkListLen }} )</view>
				</u-button>
			</view>
		</view>
		<ba-tree-picker
			ref="treePicker"
			key="verify"
			:multiple="false"
			@select-change="confirm"
			title="选择分类"
			:selectedData="selectedData"
			:localdata="classificationList"
			valueKey="id"
			textKey="name"
			childrenKey="children" />
		<SearchPopup mode="top" v-if="searchShow">
			<template v-slot:list>
				<view class="search_list">
					<u-form labelPosition="left" :model="formData" labelWidth="180" labelAlign="left" class="baseForm">
						<u-form-item label="维度:" class="required-form" borderBottom prop="warehouseId">
							<zxz-uni-data-select :localdata="dimensionList" v-model="dimension" dataValue="id" format="{name}" dataKey="name" filterable></zxz-uni-data-select>
						</u-form-item>
					</u-form>
				</view>
			</template>

			<template v-slot:operate>
				<view class="operate_box rx-bc">
					<u-button size="small" class="u-reset-button" @click="searchShow = false">取消</u-button>
					<u-button type="success" size="small" class="u-reset-button" @click="doSearch">确定</u-button>
				</view>
			</template>
		</SearchPopup>
		<!-- <view class="sparepartList">
			<uni-nav-bar fixed="true" statusBar="true" left-icon="back" title="申请备品备件" @clickLeft="back">
				<view slot="right" @click="confirm">
					<u-button class="confingBtn" size="normal" type="primary">确定{{ checkboxList.length }}</u-button>
				</view>
			</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="value" class="u-cell-value">
								<u-checkbox-group size="30" iconPlacement="right" placement="column" @change="selectItem($event, index)">
									<u-checkbox size="30" :iconSize="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="config" :defaultIndex="dimensionIndex"></u-picker>
		</view> -->
	</view>
</template>
<script>
	import { treeByPid } from '@/api/pda/workOrder.js'
	import baTreePicker from '@/components/ba-tree-picker/ba-tree-picker.vue'
	import SearchPopup from '@/pages/pda/components/searchPopup.vue'
	import { getDetailById, getBatchDetails, applySpareParts, saveNew, getInventoryDetails, getMaterielDetails } from '@/api/repair'
	export default {
		components: {
			baTreePicker,
			SearchPopup
		},
		data() {
			return {
				assetName: '',
				searchShow: false,
				formData: {},
				checkboxList: [],
				tableData: [],
				dimension: 4,
				show: false,
				categoryLevelId: 6,
				rootCategoryLevelId: '',
				classificationList: [],
				selectedData: ['6'],
				stateList: {
					0: '未质检',
					1: '已质检'
				},
				dimensionList: [
					{
						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,
				seletedAll: false
			}
		},
		onLoad(options) {
			this.id = options.id
		},
		onShow() {
			// this.getList()
			this.getTreeList()
		},
		//选择的列表长度
		computed: {
			checkListLen() {
				return this.checkboxList.length
			}
		},
		methods: {
			doSearch() {
				this.searchShow = false
				this.search()
			},
			handleSearch() {
				this.searchShow = true
			},
			getTreeList() {
				treeByPid({ ids: [6, 14] }).then(res => {
					this.classificationList = res
					this.confirm(res[0].id, res[0].name, res[0].rootCategoryLevelId)
				})
			},
			_seletedAll() {
				if (!this.seletedAll) {
					this.seletedAll = true
					this.tableData.map(item => {
						this.$set(item, 'checked', true)
						const idx = this.checkboxList.findIndex(itm => itm.id === item.id)
						if (idx === -1) {
							this.checkboxList.push(item)
						}
					})
				} else {
					this.seletedAll = false
					this.tableData.map(item => {
						this.$set(item, 'checked', false)
						const idx = this.checkboxList.findIndex(itm => itm.id === item.id)
						if (idx > -1) {
							this.checkboxList.splice(idx, 1)
						}
					})
				}
			},
			//勾选
			selectVal(e, val, index) {
				this.tableData[index].checked = !this.tableData[index].checked
				this.seletedAll = !this.tableData.some(item => !item.checked)
				const idx = this.checkboxList.findIndex(item => item.id === this.tableData[index].id)

				if (this.tableData[index].checked) {
					if (idx === -1) {
						this.checkboxList.push(this.tableData[index])
					}
				} else {
					if (idx > -1) {
						this.checkboxList.splice(idx, 1)
					}
				}
			},
			openTreePicker() {
				this.$refs.treePicker._show()
			},
			search() {
				this.pageNum = 1
				this.tableData = []
				this.getList()
			},
			scrolltolower() {
				if (this.isEnd) return
				this.pageNum++
				this.getList()
			},
			getList() {
				uni.showLoading({
					title: '加载中'
				})
				return new Promise(async (resolve, reject) => {
					try {
						let params = { assetName: this.assetName, dimension: this.dimension, pageNum: this.pageNum, size: 30, categoryLevelId: this.categoryLevelId }
						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.pageNum + (index + 1)
									}
								})
							)
							console.log(this.tableData)
						}
						this.isEnd = this.tableData.length >= this.total
						uni.hideLoading()
						resolve()
					} catch (error) {
						console.log(error)
						uni.hideLoading()
						reject()
					}
				})
			},
			confirm(id, name, rootCategoryLevelId) {
				this.rootCategoryLevelId = rootCategoryLevelId
				this.categoryLevelId = id
				this.tableData = []
				this.getList()
			},
			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: this.categoryLevelId,
					type: this.dimension,
					categoryIds,
					batchNos,
					batchIds,
					ids,
					outInDetailIds,
					materielIds
				}
				const data = await getDetailById(parmas)
				return data
			},
			async config() {
				let checkboxList = this.checkboxList.filter(item => !!item)
				console.log(checkboxList)
				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 }
					})
				}
				console.log(data)
				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)
				}
			}
		}
	}
</script>
<style lang="scss" scoped>
	.content-box {
		height: 100vh;
		overflow: hidden;
		display: flex;
		flex-direction: column;
		background-color: $page-bg;
	}

	.searchBox {
		background-color: #dedede;
		height: 90rpx;
		padding: 0 20rpx;

		.menu_icon {
			width: 60rpx;
			height: 60rpx;
			margin-right: 20rpx;
		}

		input {
			height: 70rpx;
			width: 480rpx;
			background: #f9f9f9 !important;
			padding-left: 10rpx;
			border-radius: 5rpx;
		}
	}

	.list_box {
		flex: 1;
		overflow: hidden;
		padding: 6rpx 0;

		.u-list {
			height: 100% !important;
		}
	}

	.bottom-wrapper {
		height: 80rpx;
		background: #fff;
		padding: 0 32rpx;

		/deep/ .uni-checkbox-input-checked {
			background-color: $theme-color !important;
			border-color: $theme-color !important;
		}
	}

	.listBox {
		margin-top: 8rpx;
		padding: 8rpx 24rpx;
		background: #fff;

		/deep/ .uni-checkbox-input-checked {
			background-color: $theme-color !important;
			border-color: $theme-color !important;
		}

		.listBox-con {
			width: 650rpx;
			font-weight: 400;
		}

		.listBox-top {
			margin-top: 6rpx;
			color: #090a0a;
			font-size: 28rpx;
			font-style: normal;
			font-weight: 800;
		}

		.listBox-bottom {
			color: #090a0a;
			font-size: 24rpx;
			font-style: normal;
			flex-wrap: wrap;

			.items {
				width: calc(50% - 1px);
				border-left: 1rpx solid #e3e5e5;
				border-right: 1rpx solid #e3e5e5;
				border-bottom: 1rpx solid #e3e5e5;
				box-sizing: border-box;
				word-break: break-all;
				text {
					display: inline-block;
					background: #f7f9fa;
					padding: 8rpx 10rpx;
					color: #157a2c;
				}

				&:nth-child(1),
				&:nth-child(2) {
					border-top: 1rpx solid #e3e5e5;
					margin-top: 8rpx;
				}
			}
		}
	}

	.search_list {
		min-height: 100rpx;

		/deep/ .baseForm {
			padding: 0 20rpx;
		}
	}
</style>
