<template>
	<view class="zd_container">
		<!-- 物料组盘 -->
		<nav-bar :title="title"></nav-bar>
		<view class="zd_content">
			<view class="zd_wrapper">
				<view class="zd-row border-bottom">
					<view class="zd-col-7">
						<span class="filter_label">载具编码</span>
					</view>
					<view class="zd-col-17">
						<search-box v-model="val1"/>
					</view>
				</view>
				<view class="zd-row border-bottom">
					<view class="zd-col-7">
						<span class="filter_label">物料编码</span>
					</view>
					<view class="zd-col-17">
						<input type="text" class="filter_input" v-model="currentData.material_code" @tap="toJump">
					</view>
				</view>
				<view class="zd-row border-bottom">
					<view class="zd-col-7">
						<span class="filter_label filter_input_disabled">物料名称</span>
					</view>
					<view class="zd-col-17">
						<input type="text" class="filter_input filter_input_disabled" v-model="currentData.material_name" disabled>
					</view>
				</view>
				<view class="zd-row border-bottom">
					<view class="zd-col-7">
						<span class="filter_label filter_input_disabled">物料规格</span>
					</view>
					<view class="zd-col-17">
						<input type="text" class="filter_input filter_input_disabled" v-model="currentData.material_spec" disabled>
					</view>
				</view>
				<view class="zd-row border-bottom">
					<view class="zd-col-7">
						<span class="filter_label filter_input_disabled">物料数量</span>
					</view>
					<view class="zd-col-17">
						<input type="number" class="filter_input filter_input_disabled" v-model="totalQty" disabled>
					</view>
				</view>
			</view>
			<view class="zd_wrapper grid-wraper">
				<button class="mini-btn" type="primary" size="mini" style="display: block;" @tap="addmater">添加料框</button>
				<view v-if="dataList.length" class="slide_new">
					<table>
						<thead>
							<tr>
								<th width="50%">料框号</th>
								<th width="30%">数量</th>
								<th>操作</th>
							</tr>
						</thead>
						<tbody>
							<tr v-for="(e, i) in dataList" :key="i">
								<td><input class="sin_input" :class="{ 'input-error': e.mater_frame === '' }" type="text" placeholder="请输入料框号" v-model="e.mater_frame" @blur="checkMaterFrame(i)" @input="clearError(i)" ref="materFrameInputs"></td>
								<td><input class="sin_input" type="number" v-model="e.qty" @blur="checkQty(i)"></td>
								<td><button class="mini-btn" type="primary" size="mini" style="display: block" @tap="delItem(i)">删除</button></td>
							</tr>
						</tbody>
					</table>
				</view>
			</view>
		</view>
		<view class="zd-row submit-bar">
			<button class="zd-col-6 button-default" @tap="toEmpty">清空</button>
			<button class="zd-col-16 button-primary" :class="{'button-info': JSON.stringify(currentData) === '{}' || !val1}" :disabled="disabled" @tap="_groupPlate">组盘确认</button>
		</view>
	</view>
</template>

<script>
	import NavBar from '@/components/NavBar.vue'
	import SearchBox from '@/components/SearchBox.vue'
	import NumberInput from '@/components/NumberInput.vue'
	import {groupPlate} from '@/utils/getData.js'
	export default {
		components: {
			NavBar,
			SearchBox,
			NumberInput
		},
		data() {
			return {
				title: '',
				val1: '',
				totalQty: null,
				currentData: {},
				disabled: false,
				dataList: []
			};
		},
		watch: {
			dataList: {
				deep: true,
				handler() {
					this.updateTotalQty()
				}
			}
		},
		onLoad (options) {
			this.title = options.title
		},
		onShow() {
			if (this.$store.getters.publicObj !== '') {
				this.currentData = this.$store.getters.publicObj
			}
		},
		methods: {
			toJump () {
				uni.navigateTo({
					url: '/pages/manage/common/cxwl?title=查询物料'
				})
			},
			addmater () {
				this.validateMaterFrames()
				this.dataList.push({mater_frame: null, qty: 0.000})
			},
			delItem (i) {
				this.dataList.splice(i, 1)
				this.validateMaterFrames()
			},
			toEmpty () {
				this.val1 = ''
				this.currentData = {}
				this.totalQty = null
				this.dataList = []
				this.disabled = false
				this.$store.dispatch('setPublicObj', '')
			},
			checkMaterFrame (index) {
				const { mater_frame } = this.dataList[index]
				if (!mater_frame) return
				const isDuplicate = this.dataList.some((item, i) => i !== index && item.mater_frame === mater_frame)
				if (isDuplicate) {
					uni.showToast({
						title: '料框号重复',
						icon: 'none'
					})
					// 清空当前料框号
					this.dataList[index].mater_frame = ''
				}
			},
			checkQty (index) {
				const { qty } = this.dataList[index]
				if (qty < 0) {
					uni.showToast({
						title: '数量必须为非负数',
						icon: 'none'
					})
					// 重置数量为0
					this.dataList[index].qty = 0.000
				}
			},
			clearError(index) {
			  if (this.dataList[index].mater_frame) {
				this.$refs.materFrameInputs[index].$el.style.borderColor = ''
			  }
			},
			updateTotalQty() {
			  this.totalQty = this.dataList.reduce((total, item) => total + parseFloat(item.qty), 0)
			},
			validateMaterFrames () {
				let isValid = true
				for (let i = 0; i < this.dataList.length; i++) {
					if (!this.dataList[i].mater_frame) {
						this.$refs.materFrameInputs[i].$el.style.borderColor = 'red'
						this.scrollToView(this.$refs.materFrameInputs[i])
						isValid = false
					} else {
						this.$refs.materFrameInputs[i].$el.style.borderColor = ''
					}
				}
				return isValid
			},
			scrollToView (element) {
				if (element) {
					element.$el.scrollIntoView({ behavior: 'smooth', block: 'center' })
				}
			},
			async _groupPlate () {
				this.disabled = true
				if (JSON.stringify(this.currentData) === '{}' || !this.val1) {
					this.disabled = false
					return
				}
				if (!this.validateMaterFrames()) {
					this.disabled = false
					return
				}
				try {
					let res = await groupPlate(this.currentData.material_id, this.totalQty, this.val1, this.dataList)
					uni.showToast({
						title: res.message,
						icon: 'none'
					})
					this.toEmpty()
					this.disabled = false
				} catch (e) {
					this.disabled = false
				}
			}
		}
	}
</script>

<style lang="stylus" scoped>
.slide_new
	table
		table-layout auto
		th,td
			&:first-child
				box-shadow: none
.sin_input
	width 100%
.input-error
	border-color #ff8227
</style>
