<template>
	<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="keyWord" placeholder="请输入关键字搜索" class="searchInput" />

				<view class="rx-sc">
					<image class="menu_icon" src="~@/static/pda/menu.svg" @click="handleSearch"></image>
					<u-button @click="doSearch" 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 list" :key="index" @change="e => selectVal(e, item, index)">
					<label class="listBox rx-bs">

						<view class="listBox-sel">
							<checkbox
								v-if='item.rootCategoryLevelId != 11 || (item.rootCategoryLevelId == 11 && item.status != 1)'
								: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 class="code">{{ item.rootCategoryLevelId == 4 ?  item.codeNumber :  item.code}}
								</view>
							</view>

							<view class="listBox-bottom rx">
								<view v-for="(itm, index) in tableH(item.rootCategoryLevelId)" :key="index"
									class="items" v-if="!itm.formatter">
									<text>{{ itm.label }}</text>{{ item[itm.prop] }}
								</view>




								<view class="items"
									v-if='item.rootCategoryLevelId != 11 && item.rootCategoryLevelId != 4 '>
									<text>可用库存</text>{{ item.availableCountBase }} {{item.unit}}
								</view>

								<view class="items" v-if=' item.rootCategoryLevelId == 4 '>
									<text>状态</text>{{ stateList[Number(item.runStatus)] }}
								</view>


								<!-- 		<view class="items"
									v-if='item.rootCategoryLevelId == 1 '>
									<text>包装库存</text>{{ item.packingCountBase }} {{item.minUnit}}
								</view> -->

								<view class="items" v-if='item.rootCategoryLevelId == 11'>
									<text
										:style="{ color:  item.status == 0 ? '#157A2C' :'#FFA929' }">状态{{ item.status == 0 ? '空闲' : item.status == 1 ? '占用' : ''}}</text>
								</view>




								<view class="items" v-if='item.rootCategoryLevelId == 11'>
									<text>位置</text>{{ item.region }}
								</view>




							</view>

						</view>


					</label>

				</checkbox-group>



				<view v-if='list.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="jumpAdd">
					<view> 选择( {{ checkListLen }} ) </view>
				</u-button>
			</view>
		</view>

		<ba-tree-picker ref="treePicker" key="verify" :multiple="false" @select-change="confirm" title="选择分类"
			: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="warehouseList" v-model="formData.warehouseId"
								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="searchCancel">
						重置
					</u-button>


					<u-button type="success" size="small" class="u-reset-button" @click="doSearch">
						确定
					</u-button>

				</view>
			</template>

		</SearchPopup>

	</view>
</template>

<script>
	import baTreePicker from '@/components/ba-tree-picker/ba-tree-picker.vue'
	import {
		tableHeader
	} from '../../common.js'
	import {
		treeByPid,
		pageeLedgerMain,
		assetPage,
		getWarehouseList
	} from '@/api/pda/workOrder.js'


	import SearchPopup from '../../components/searchPopup.vue'


	let [isEnd] = [false]
	export default {
		components: {
			baTreePicker,
			SearchPopup
		},
		data() {
			return {

				keyWord: null,
				rootCategoryLevelId: null,
				categoryLevelId: null,
				classificationList: [],
				treePickerShow: false,
				list: [],
				page: 1,


				seletedAll: false, //全选状态
				memoList: [],

				isType: null,
				taskId: null,

				pid: null, // 上个页面id
				storageKey: null,

				formData: {
					produceRoutingId: ''
				},
				warehouseList: [],

				searchShow: false,

				stateList: ['启动', '空闲', '运行', '故障', '检修', '停机', '待料', '占用'],
				classIds: []



			}
		},

		//选择的列表长度
		computed: {
			checkListLen() {
				return this.memoList.length
			}

		},

		onLoad(option) {
			this.pid = option.id
			this.isType = option.isType
			if (option.taskId == 'undefined') {
				this.taskId = null
			} else {
				this.taskId = option.taskId || null
			}
			if (Object.prototype.hasOwnProperty.call(option, 'classIds')) {
				this.classIds = option.classIds
			}

			if (option.storageKey) {
				this.storageKey = option.storageKey

				this.memoList = []

				if (this.isType == 'feed') {
					let _arr = (this.storageKey && uni.getStorageSync(this.storageKey)) || []
					this.memoList = [..._arr[0].modelList, ..._arr[0].equipmentList, ..._arr[0].instanceList, ..._arr[0]
						.aridRegionList, ..._arr[0].turnover, ..._arr[0].palletList, ..._arr[0].revolvingDiskList, ...
						_arr[0].semiProductList
					]



				} else if (this.isType == 'pick') {
					this.memoList = (this.storageKey && uni.getStorageSync(this.storageKey)) || []
				} else if (this.isType == 'job') {
					let _obj = (this.storageKey && uni.getStorageSync(this.storageKey)) || {}

					if (Object.prototype.hasOwnProperty.call(_obj, 'turnover')) {
						this.memoList = this.memoList.concat(_obj.turnover)
					} else if (Object.prototype.hasOwnProperty.call(_obj, 'equipmentList')) {
						this.memoList = this.memoList.concat(_obj.equipmentList)
					}

				}
				
				else if (this.isType == 'zdy') {
					let _arr = (this.storageKey && uni.getStorageSync(this.storageKey)) || []
				
					if (Object.prototype.hasOwnProperty.call(_arr[0], 'turnover')) {
						this.memoList = this.memoList.concat(_arr[0].turnover)
					} else if (Object.prototype.hasOwnProperty.call(_arr[0], 'equipmentList')) {
						this.memoList = this.memoList.concat(_arr[0].equipmentList)
					}
				
				}



			}

			this.getTreeList()

			this.getWarehouseFn()
		},

		onUnload() {
			if (this.storageKey) {
				uni.removeStorage(this.storageKey)
			}

		},



		methods: {
			_seletedAll() {

				if (!this.seletedAll) {
					this.seletedAll = true

					this.list.map(item => {
						this.$set(item, 'checked', true)
						const idx = this.memoList.findIndex(itm => itm.id === item.id)
						if (idx === -1) {
							this.memoList.push(item)
						}
					})



				} else {
					this.seletedAll = false
					this.list.map(item => {
						this.$set(item, 'checked', false)

						const idx = this.memoList.findIndex(itm => itm.id === item.id)
						if (idx > -1) {
							this.memoList.splice(idx, 1)
						}

					})
				}
			},

			openTreePicker() {
				this.$refs.treePicker._show()

			},
			tableH(type) {
				return tableHeader(type)
			},

			getTreeList() {
				let params = {}
				if (this.isType == 'feed') {
					params.ids = [1, 4, 5, 8, 10, 11, 13, 14, 23, 26]
				} else if (this.isType == 'pick') {
					params.ids = [1, 5, 7, 8, 10, 13, 14, 23, 26]
				} else if (this.isType == 'job') {
					params['ids'] = [4, 7]
				}  else if (this.isType == 'zdy') {
					params['ids'] =  JSON.parse(this.classIds);
				} 

				treeByPid(params).then(res => {
					this.classificationList = res
					this.confirm([res[0].id], res[0].name, res[0].rootCategoryLevelId)
				})
			},

			confirm(id, name, rootCategoryLevelId) {
				this.rootCategoryLevelId = rootCategoryLevelId
				this.categoryLevelId = id

				this.list = []
				this.getList()
			},


			doSearch() {
				this.list = []
				this.getList()
				this.searchShow = false
			},

			scrolltolower() {
				if (isEnd) return
				this.page++
				this.getList()
			},

			getList() {
				let param = {
					categoryLevelId: this.categoryLevelId,
					keyWord: this.keyWord,
					pageNum: this.page,
					size: 100,
					taskId: this.taskId

				}

				if (this.rootCategoryLevelId == '11') { // 干燥区特殊处理
					param.size = 5
				}
				isEnd = false
				let URL = null
				if (this.isType == 'pick') { // 领料
					param.dimension = 1
					// URL = this.rootCategoryLevelId == 1 ? pageeLedgerMain : assetPage
					URL = pageeLedgerMain
				} else if (this.isType == 'feed') { // 投料
					URL = assetPage
				} else if (this.isType == 'job' || this.isType == 'zdy') { // 报工
					URL = assetPage
				}

				URL(param).then(res => {
					if (this.rootCategoryLevelId == '11') {

						res.list.forEach(e => {
							if (e.aridRegionList && e.aridRegionList.length != 0) {
								e.aridRegionList.map(i => {
									const checked =
										this.memoList.findIndex(itm => itm.id === i.id) > -1

									let obj = {
										checked,
										name: e.name,
										region: e.extInfo.region,
										rootCategoryLevelId: e.rootCategoryLevelId,
										...i,
										instanceId: i.id,
									}
									this.list.push(obj)

								})
							}
						})




					} else {
						this.list.push(
							...res.list.map(i => {
								const checked =
									this.memoList.findIndex(itm => itm.id === i.id) > -1

								const warehouseId = i.pathIds && i.pathIds.split(',')[0]

								return {
									checked,
									warehouseId,
									...i,
									instanceId: i.id,
								}
							})
						)
					}


					isEnd = this.list.length >= res.count


				})

			},

			//勾选
			selectVal(e, val, index) {
				console.log(val)
				if (val.rootCategoryLevelId == 11 && val.status == 1) {
					return false
				}
				this.list[index].checked = !this.list[index].checked
				this.seletedAll = !this.list.some(item => !item.checked)
				const idx = this.memoList.findIndex(
					item => item.id === this.list[index].id
				)

				if (this.list[index].checked) {
					if (idx === -1) {
						this.memoList.push(this.list[index])
					}
				} else {
					if (idx > -1) {
						this.memoList.splice(idx, 1)
					}
				}

			},

			handleSearch() {
				this.searchShow = true
			},

			searchCancel() {
				this.list = []
				this.page = 1
				this.getList()
				this.searchShow = false
			},


			//跳转回添加页面
			jumpAdd() {

				if (this.isType == 'pick' || this.isType == 'feed' || this.isType == 'job' || this.isType == 'zdy') {
					uni.$emit('setSelectList', this.memoList, this.pid)
					uni.navigateBack()
				}

			},

			getWarehouseFn() {
				getWarehouseList().then(res => {
					this.warehouseList = res
				})
			},
		}
	}
</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;

				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>