<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-24 filter_select">
						<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-24 filter_select">
						<uni-data-select v-model="index" :localdata="options" @change="selectChange"></uni-data-select>
					</view>
				</view>
				<view class="zd-row">
					<!-- <view class="zd-col-1">
					</view> -->
					<view class="zd-col-6" style="width: 27%;">
						<button class="mini-btn" size="mini" style="display: block; margin-top: 9px; width: 103%;" type="primary" @tap="toScanAdd">扫码插入</button>
					</view>
					<view class="zd-col-6" style="width: 22%;">
						<button class="mini-btn" size="mini" style="display: block; margin-top: 9px; width: 103%;" type="primary" @tap="toAdd">插入行</button>
					</view>
					<view class="zd-col-6" style="width: 22%;">
						<button class="mini-btn" size="mini" style="display: block; margin-top: 9px; width: 103%;" type="primary" @tap="toDel">删除行</button>
					</view>
					<view class="zd-col-6" style="width: 22%;">
						<button class="mini-btn" size="mini" style="display: block; margin-top: 9px; width: 103%;" type="primary" @tap="toCopy">复制行</button>
					</view>
				</view>
			</view>
			<view class="zd_wrapper grid-wraper">
				<view class="slide_new">
					<table>
						<thead>
							<tr>
								<th>序号</th>
								<th>卷号</th>
								<th>物料编码</th>
								<th>物料名称</th>
								<th>数量</th>
								<th>单位</th>
							</tr>
						</thead>
						<tbody>
							<tr v-for="(e, i) in dataList" :key="i" :class="{'checked': e.mid === pkId}">
								<td @tap="toCheck(e)">{{i+1}}</td>
								<td><input type="text" class="sin_input" style="width: 135px;" v-model="e.container_code"></td>
								<td @tap="toJump(e)">{{e.material_code}}</td>
								<td>{{e.material_name}}</td>
								<td><input type="number" class="sin_input" v-model="e.qty" @blur="handleBlur(e)"></td>
								<td>{{e.measure_unit_id}}</td>
							</tr>
						</tbody>
					</table>
				</view>
			</view>
		</view>
		<view class="zd-row submit-bar">
			<!-- <button class="zd-col-6 button-default" @tap="clearUp">清空</button> -->
			<!-- <button class="zd-col-11 button-primary" :class="{'button-info': !val1 || !dataList.length || !index}" :disabled="disabled" @tap="_blanking">确认下料</button> -->
			<button class="zd-col-22 button-primary" :class="{'button-info': !val1 || !dataList.length || !index}" :disabled="disabled" @tap="_blanking">确认下料</button>
		</view>
	</view>
</template>

<script>
	import NavBar from '@/components/NavBar.vue'
	import SearchBox from '@/components/SearchBox.vue'
	import {getRegions, selectMaterials, blanking} from '@/utils/getData4.js'
	export default {
		components: {
			NavBar,
			SearchBox
		},
		data() {
			return {
				title: '',
				val1: '',
				dataList: [],
				pkId: '',
				pkObj: {},
				currentData: {},
				options: [],
				index: '',
				disabled: false
			};
		},
		onLoad (options) {
			this.title = options.title
		},
		onShow() {
			if (this.$store.getters.publicObj !== '') {
				this.currentData = this.$store.getters.publicObj
				this.pkId = ''
				this.dataList.map((item) => {
					if (this.pkObj.mid === item.mid) {
						item.material_name = this.currentData.material_name
						item.material_code = this.currentData.material_code
						item.measure_unit_id = this.currentData.measure_unit_id
					}
				})
			}
		},
		created () {
			this._getRegions1()
		},
		methods: {
			async _getRegions1 () {
				try {
					let res = await getRegions()
					if (res) {
						this.options = res.data
					} else {
						this.options =[]
					}
				} catch (e) {
					this.options = []
				}
			},
			selectChange (e) {
				this.index = e
			},
			toCheck (e) {
				this.pkId = this.pkId === e.mid ? '' : e.mid
				this.pkObj = this.pkId === e.mid ? e : {}
			},
			handleBlur (e) {
				if (e.qty) {
					if (e.qty < 0) {
						e.qty = 0
					} else {
						e.qty = e.qty.replace(/[^0-9]/g, '')
						e.qty = e.qty.replace(/^0+/, '') || '0'
					}
				} else {
					// uni.showToast({
					// 	title: '数量必填',
					// 	icon: 'none'
					// })
				}
			},
			toJump (e) {
				this.pkId = this.pkId === e.mid ? '' : e.mid
				this.pkObj = this.pkId === e.mid ? e : {}
				this.pkId = ''
				uni.navigateTo({
					url: '/pages/ftdl/mater-list0?title=查询物料'
				})
			},
			toScanAdd () {
				uni.scanCode({
					success: (res) => {
						// console.log('扫码成功:', res.result);
						const parts = res.result.split(';')
						if (parts.length !== 5) {
							uni.showToast({
								title: '二维码格式不正确，请扫描符合格式的二维码',
								icon: 'none'
							})
							return
						}
						let currObj = {
							mid: 'mid_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9),
							container_code: parts[0],
							material_code: parts[1],
							material_name: parts[2],
							qty: parts[3],
							measure_unit_id: parts[4],
						}
						// 检查是否已存在相同卷号
						const exists = this.dataList.some(item => item.container_code === currObj.container_code)
						if (exists) {
							uni.showToast({
								title: '已存在',
								icon: 'none'
							})
							return
						}
						this.dataList.push(currObj)
					},
					fail: (err) => {
						console.log('扫码失败:', err)
						// uni.showToast({
						// 	title: err + '扫码失败',
						// 	icon: 'none'
						// })
					}
				})
			},
			toAdd () {
				let currObj = {
					mid: 'mid_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9),
					container_code: '',
					material_code: '编码',
					material_name: '名称',
					qty: '1',
					measure_unit_id: '单位'
				}
				this.dataList.push(currObj)
			},
			toDel () {
				if (!this.pkId) {
					return
				}
				this.dataList = this.dataList.filter(item => item.mid !== this.pkObj.mid)
			},
			toCopy () {
				if (!this.pkId) {
					return
				}
				// let original = this.dataList.find(item => item.mid === this.pkObj.mid)
				const copy = JSON.parse(JSON.stringify(this.pkObj))
				// 更新mid为新生成的唯一值
				copy.mid = 'mid_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
				// 添加到原数组
				this.dataList.push(copy)
				this.pkId = ''
			},
			clearUp () {
				this.val1 = ''
				this.index = ''
				this.dataList = []
				this.disabled = false
			},
			async _blanking () {
				this.disabled = true
				if (!this.val1 || !this.dataList.length || !this.index) {
					this.disabled = false
					return
				}
				try {
					let res = await blanking(this.val1, this.dataList, this.index)
					if (res.code === '200') {
						this.val1 = ''
						this.index = ''
						this.dataList = []
						uni.showToast({
							title: res.desc,
							icon: 'none'
						})
					} else {
						uni.showToast({
							title: res.desc,
							icon: 'none'
						})
					}
					this.disabled = false
				} catch (e) {
					this.disabled = false
				}
			}
		}
	}
</script>
<style lang="stylus">
	.checked
		background #ff0
</style>