<template>
	<view class="content-box">
		<uni-nav-bar fixed="true" statusBar="true" left-icon="back" :title="title" background-color="#F7F9FA"
			color="#000" @clickLeft="back" right-icon="scan" @clickRight="HandlScanCode">
		</uni-nav-bar>

		<view class="list_box">
			<u-list @scrolltolower="scrolltolower">

				<view class="card_box">
					<workOrderBom :item='objData' v-if='objData' @handleScan='handleScan'></workOrderBom>

					<paramBom v-if='paramDetailList.length != 0' :list='paramDetailList'></paramBom>

					<deviceBom v-if='objData.equipmentList.length != 0' :list='objData.equipmentList'></deviceBom>

					<modelBom v-if='objData.modelList.length != 0' :list='objData.modelList' pattern='job'
						ref='modelRef'>
					</modelBom>



					<jobBom :item='objData' :palletList='objData.palletList' :notFormed='objData.notFormedList'
						@penalize='penalize' @modeNum='modeNum'></jobBom>

					<oneJobBom v-if='objData.instanceList &&  objData.instanceList.length != 0' :item='objData'
						:list='objData.instanceList'>
					</oneJobBom>

					<byProductBom v-if='objData.productRecycleList.length != 0 ' :list='objData.productRecycleList'
						@penalize='penalize'>
					</byProductBom>

					<turnoverBom v-if='objData.turnover.length != 0' :list='objData.turnover' :wordItem='objData'
						pattern='job' @handleScan='handleScan'>
					</turnoverBom>



					<aridRegion v-if='objData.aridRegionList.length != 0' :list='objData.aridRegionList'
						:remainingTime='remainingTime' @handleScan='handleScan' :isType='true'></aridRegion>

					<view class="operate_box rx-sc">
						<u-button size="small" class="u-reset-button" type="success" @click="handAdd">手动添加</u-button>
					</view>

				</view>

			</u-list>
		</view>


		<view class="bottom-wrapper">
			<view class="btn_box" @click="save">一键报工</view>
		</view>


		<SearchPopup mode="bottom" 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' dataKey="name" filterable format='{name}'></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="popupOk">
						确定
					</u-button>

				</view>
			</template>

		</SearchPopup>


	</view>
</template>

<script>
	import {
		getByIdReport,
		getByCodeReport,
		jobSave
	} from '@/api/pda/jobBooking.js'

	import {
		scanLedger,
		getWarehouseList,

	} from '@/api/pda/workOrder.js'


	import workOrderBom from '../../feeding/components/workOrderBom.vue'
	import deviceBom from '../../feeding/components/deviceBom.vue'
	import modelBom from '../../feeding/components/modelBom.vue'
	import jobBom from '../components/jobBom.vue'
	import oneJobBom from '../components/oneJobBom.vue'
	import byProductBom from '../components/byProductBom'
	import turnoverBom from '../components/turnoverBom.vue'
	import aridRegion from '../../feeding/components/aridRegion.vue'
	import paramBom from '../../feeding/components/paramBom.vue'
	import SearchPopup from '../../components/searchPopup.vue'


	export default {

		components: {
			workOrderBom,
			deviceBom,
			modelBom,
			jobBom,
			oneJobBom,
			byProductBom,
			turnoverBom,
			aridRegion,
			paramBom,
			SearchPopup
		},
		data() {
			return {
				title: '',

				objData: {
					equipmentList: [],
					modelList: [],
					turnover: [],
					productRecycleList: [],
					aridRegionList: [],
					palletList: [],
					workReportInfo: {},

					notFormedList: [], // 报工-不合格

				},


				searchShow: false,

				warehouseList: [],
				formData: {
					warehouseId: ''
				},
				penalizeIndex: null,


				paramDetailList: [],
				remainingTime: 0,



				id: null,
				taskId: null,

			}
		},
		onLoad(options) {
			this.title = options.taskName ? options.taskName + '-报工' : '报工'
			this.id = options.id
			this.taskId = options.taskId
			this.getList()
		},

		onShow() {
			uni.$off("setSelectList");

			uni.$on("setSelectList", (selectList, id) => {

				let turnover = []
				let equipmentList = [] // 生产设备
				let isEquipment = this.objData.equipmentList.length > 0 ? true : false // 判断是否有设置


				selectList.forEach(f => {
					if (f.rootCategoryLevelId == 4) { // 生产设备
						if (isEquipment) {
							equipmentList = this.objData.equipmentList
						} else {
							equipmentList = equipmentList.concat(f)
						}


					}
					if (f.rootCategoryLevelId == 7) { // 周转车
						turnover = turnover.concat(f)
					}
				})



				this.$set(this.objData, 'equipmentList', equipmentList)
				this.$set(this.objData, 'turnover', turnover)
				this.$forceUpdate()



			});

		},

		methods: {


			// 相机扫码
			HandlScanCode() {
				// CX-EQ-YLSJL-008	  设备
				// M001 M002 模具 
				// 周转车 w0300000003140004
				// this.scanItAllData('M002')
				// return false

				let _this = this
				uni.scanCode({
					success: function(res) {
						_this.scanItAllData(res.result)
					}
				})

			},

			scanItAllData(result) {
				scanLedger(result).then(res => {
					if (res.length == 1 && res[0].rootCategoryLevelId == 4) { // 设备
						if (this.objData.equipmentList.length == 0) {
							this.objData.equipmentList = res
							this.$forceUpdate()
						} else {
							if (this.objData.equipmentList[0].instanceId != res[0].instanceId) {
								uni.showToast({
									title: '设备不匹配',
									icon: 'none'
								})
							} else {
								uni.showToast({
									title: '设备匹配成功',
									icon: 'none'
								})
							}
						}
					}

					if (res.length >= 1 && res[0].rootCategoryLevelId == 5) { // 磨具
						if (this.objData.modelList.length == 0) {
							this.objData.modelList = res
							this.$forceUpdate()
						} else {
							if (this.objData.modelList[0].instanceId != res[0].instanceId) {
								uni.showToast({
									title: '模具不匹配',
									icon: 'none'
								})
							} else {
								uni.showToast({
									title: '设备匹配成功',
									icon: 'none'
								})
							}
						}
					} else if (res.length == 1 && res[0].rootCategoryLevelId == 7) { // 周转车

						let isFals = this.objData.turnover.some(m => m.code == result)
						if (isFals) {
							uni.showToast({
								title: '周转车已存在',
								icon: 'none'
							})
							return false
						}
						this.objData.turnover.push(res[0])
						this.$forceUpdate()

					}

				})
			},


			handleScan(id, type) {


				let _this = this
				uni.scanCode({
					success: function(res) {
						_this.scanData(res.result, type, id)
					}
				})
			},


			scanData(result, type, id) {
				if (type == 'wordOrder') {
					getByCodeReport(result, this.taskId).then(res => {
						this.objData = res

						if (!this.objData.hasOwnProperty('turnover')) {
							this.objData['turnover'] = []
						}
						if (!this.objData.hasOwnProperty('aridRegionList')) {
							this.objData['aridRegionList'] = []
						}

					})
				} else if (type == 'turnover') {

					let isFals = this.objData.turnover.some(m => m.code == result)
					if (isFals) {
						uni.showToast({
							title: '周转车已存在',
							icon: 'none'
						})
						return false
					}

					getByCodeReport(result, this.taskId).then(res => {
						this.objData.turnover[id] = res
					})

				}

			},



			getList() {
				getByIdReport(this.id, this.taskId).then(res => {
					this.objData = res
					if (!this.objData.hasOwnProperty('turnover')) {
						this.objData['turnover'] = []
					}
					if (!this.objData.hasOwnProperty('aridRegionList')) {
						this.objData['aridRegionList'] = []
					}

					if (!this.objData.hasOwnProperty('instanceList')) {
						this.objData['instanceList'] = []
					}





					this.objData.palletList = [{
						categoryLevelId: '',
						categoryLevelName: '',
						categoryId: '',
						rootCategoryLevelId: '',
						code: '',
						name: '',
						specification: '',
						brandNum: '',
						modelType: '',
						quantity: '',
						unit: ''
					}]
					this.objData.workReportInfo = {
						formingNum: null,
						formingWeight: null,
						formedNum: null,
						formedWeight: null,
						taskId: this.taskId

					}

					this.objData.notFormedList = [{
						notFormedNum: null,
						notFormedWeight: null,
						weightUnit: res.weightUnit,
						unit: res.unit,
						warehouseId: null, // 处置 仓库id
					}]

					if (this.objData.instanceList.length > 0) { // 预制体报工
						this.objData.workReportInfo.formedNum = this.objData.instanceList.length
					}


					this.objData.workReportInfo.formingNum = res.formingNum
					this.objData.workReportInfo.formingWeight = res.formingWeight
					this.objData.workReportInfo.unit = res.unit
					this.objData.workReportInfo.weightUnit = res.weightUnit
					this.objData.workReportInfo.workOrderId = res.workOrderId

					this.paramDetailList = []

					this.paramDetailList = res.paramDetailList.map(m => {
						if (m.extInfo.textType == 5) {
							this.remainingTime = m.extInfo.remainingTime
						}
						return {
							...m.extInfo
						}
					})




				})
			},

			scrolltolower() {},

			handAdd() {
				const storageKey = Date.now() + "";
				uni.setStorageSync(storageKey, this.objData || {});
				uni.navigateTo({
					url: `/pages/pda/workOrder/search/index?storageKey=${storageKey}&isType=job&taskId=${this.taskId}`
				})
			},


			penalize(index) {
				if (index || index == 0) {
					this.penalizeIndex = index
					this.formData.warehouseId = this.objData.productRecycleList[this.penalizeIndex].warehouseId || ''
				} else {
					this.penalizeIndex = null
					this.formData.warehouseId = this.objData.notFormedList[0].warehouseId || ''

				}
				this.$forceUpdate()

				if (this.warehouseList.length == 0) {
					getWarehouseList().then(res => {
						this.warehouseList = res
						this.searchShow = true
					})
				} else {
					this.searchShow = true
				}
			},

			inputChange(e) {
				console.log(e)
			},

			searchCancel() {
				this.searchShow = false
			},
			popupOk() {
				if (this.penalizeIndex == null) {
					this.$set(this.objData.notFormedList[0], 'warehouseId', this.formData.warehouseId || null)

				} else {
					this.objData.productRecycleList[this.penalizeIndex].warehouseId = this.formData.warehouseId
				}
				this.$forceUpdate()
				this.searchShow = false

			},

			modeNum(num) {
				if (this.objData.modelList.length == 0) {
					return false
				}
				this.$refs.modelRef.setNum(num)
			},




			save() {
				console.log(this.objData)
				if (!this.objData.workReportInfo['formedNum'] && this.objData.workReportInfo['formedNum'] != 0) {
					uni.showToast({
						title: '请输入合格品数量',
						icon: 'none'
					})
					return false
				}
				// if (!this.objData.workReportInfo['formedWeight'] && this.objData.workReportInfo['formedWeight'] != 0) {
				// 	uni.showToast({
				// 		title: '请输入合格品重量',
				// 		icon: 'none'
				// 	})
				// 	return false
				// }




				if (this.objData.notFormedList[0].notFormedNum > 0 && !this.objData.notFormedList[0].warehouseId) {
					uni.showToast({
						title: '请点击不合格品处置，选择仓库',
						icon: 'none'
					})
					return false
				}

				if (this.objData.productRecycleList.length > 0) {
					let bol
					bol = this.objData.productRecycleList.every(e => {
						return e.recycleQuantity >= 0 && e.warehouseId
					})


					if (!bol) {
						uni.showToast({
							title: '请选择副产品回收处置',
							icon: 'none'
						})
						return false
					}

				}


				if (this.objData.instanceList.length > 0) {
					let bol
					let _i
					bol = this.objData.instanceList.every((e, i) => {
						_i = i + 1
						return e.extInfo.hasOwnProperty('taskId') && e.extInfo.taskId
					})

					if (!bol) {
						uni.showToast({
							title: `请完善第${_i}处置方式`,
							icon: 'none'
						})
						return false
					}
				}




				jobSave(this.objData).then(res => {
					uni.navigateBack()
				})



			}
		}
	}
</script>

<style lang="scss" scoped>
	.content-box {
		height: 100vh;
		overflow: hidden;
		display: flex;
		flex-direction: column;

	}

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

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

		.card_box {
			padding: 16rpx 24rpx;
		}



	}

	.bottom-wrapper {
		.btn_box {
			width: 750rpx;
			height: 88rpx;
			line-height: 88rpx;
			background: $theme-color;
			text-align: center;
			font-size: 36rpx;
			font-style: normal;
			font-weight: 400;
			color: #fff;
		}
	}


	.operate_box {
		padding: 10rpx 160rpx;

		/deep/ .u-button {
			width: 160rpx;
		}
	}

	.search_list {
		min-height: 500rpx;
		padding: 0 32rpx;
	}
</style>