<template>
	<view class="zd_container">
		<!-- 物料组盘 -->
		<nav-bar :title="title"></nav-bar>
		<view class="zd_content">
			<view class="zd_wrapper">
				<view class="is-required">
					<view class="filter_label">{{$t('label.CarrierCode')}}</view>
					<search-box v-model="val1"/>
				</view>
				<view>
					<view class="filter_label">{{$t('label.MaterialCode')}}</view>
					<input type="text" class="filter_input" v-model="currentData.material_code" @tap="toJump">
				</view>
				<view>
					<view class="filter_label">{{$t('label.MaterialName')}}</view>
					<input type="text" class="filter_input filter_input_disabled" v-model="currentData.material_name" disabled>
				</view>
				<view>
					<view class="filter_label">{{$t('label.MaterialSpecification')}}</view>
					<input type="text" class="filter_input filter_input_disabled" v-model="currentData.material_spec" disabled>
				</view>
				<view>
					<view class="filter_label">{{$t('label.MaterialQuantity')}}</view>
					<view class="zd-row">
						<view class="zd-col-20"><input type="number" class="filter_input filter_input_disabled" v-model="totalQty" disabled></view>
						<view class="zd-col-4 filter_unit">{{currentData.base_unit_name}}</view>
					</view>
				</view>
			</view>
			<view class="zd_wrapper grid-wraper">
				<button class="mini-btn" type="primary" size="mini" style="display: block;" @tap="addmater">{{$t('button.AddMaterialBox')}}</button>
				<view v-if="dataList.length" class="slide_new">
					<table>
						<thead>
							<tr>
								<th width="50%">{{$t('th.MaterialBoxNumber')}}</th>
								<th width="30%">{{$t('Quantity')}}</th>
								<th>{{$t('button.Operation')}}</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" 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)">{{$t('button.Delete')}}</button></td>
							</tr>
						</tbody>
					</table>
				</view>
			</view>
		</view>
		<view class="zd-row submit-bar">
			<button class="zd-col-6 button-default" @tap="toEmpty">{{$t('button.clear')}}</button>
			<button class="zd-col-16 button-primary" :class="{'button-info': JSON.stringify(currentData) === '{}' || !val1}" :disabled="disabled" @tap="_groupPlate">{{$t('button.confirm')}}</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=' + this.$t('home.QueryMaterials')
				})
			},
			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: this.$t('toast.boxnotduplicated'),
						icon: 'none'
					})
					// 清空当前料框号
					this.dataList[index].mater_frame = ''
				}
			},
			checkQty (index) {
				const { qty } = this.dataList[index]
				if (qty < 0) {
					uni.showToast({
						title: this.$t('toast.quantitynonnegative'),
						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>
