<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> -->
						<span class="filter_label">{{$t('filter.point')}}</span>
					</view>
					<view class="zd-col-24 filter_select">
						<search-box
						v-model="val1"
						@handleChange="handleChange"
						/>
					</view>
				</view>
				<view class="zd-row">
					<button class="zd-col-6 button-primary ftsize1" @tap="toScanAdd">{{$t('button.scan-add')}}</button>
					<button class="zd-col-5 button-primary ftsize1" @tap="toAdd">{{$t('button.add-row')}}</button>
					<button class="zd-col-5 button-primary ftsize1" @tap="toDel">{{$t('button.del-row')}}</button>
					<button class="zd-col-6 button-primary ftsize1" @tap="toCopy">{{$t('button.copy-row')}}</button>
				</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> -->
								<th>{{$t('grid.number')}}</th>
								<th>{{$t('grid.roll-number')}}</th>
								<th>{{$t('grid.material-code')}}</th>
								<th>{{$t('grid.material-name')}}</th>
								<th>{{$t('grid.quantity')}}</th>
								<th>{{$t('grid.unit')}}</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-primary" @tap="searchList">查询</button>
			<button class="zd-col-7 button-primary" :class="{'button-info': !val1 || !dataList.length}" :disabled="disabled" @tap="_materialBinding">物料绑定</button>
			<button class="zd-col-7 button-primary" :class="{'button-info': !val1}" :disabled="disabled2" @tap="_vehicleBinding">空载具绑定</button> -->
			<button class="zd-col-8 button-primary" @tap="searchList">{{$t('button.search')}}</button>
			<button class="zd-col-7 button-primary" :class="{'button-info': !val1 || !dataList.length}" :disabled="disabled" @tap="handleConfirm">{{$t('button.material-bind')}}</button>
			<button class="zd-col-7 button-primary" :class="{'button-info': !val1}" :disabled="disabled2" @tap="handleConfirm2">{{$t('button.empty-vehicle-bind')}}</button>
		</view>
	</view>
</template>

<script>
	import NavBar from '@/components/NavBar.vue'
	import SearchBox from '@/components/SearchBox.vue'
	import { confirmAction } from '@/utils/utils.js'
	import {selectMaterialByPointCode, materialBinding, vehicleBinding} from '@/utils/getData4.js'
	export default {
		components: {
			NavBar,
			SearchBox
		},
		data() {
			return {
				title: '',
				val1: '',
				dataList: [],
				pkId: '',
				pkObj: {},
				currentData: {},
				reload: false,
				status: 'more',
				contentText: {
					contentdown: '查看更多',
					contentrefresh: '加载中',
					contentnomore: '没有更多'
				},
				totalCount: 0,
				pageNum: 1,
				pageSize: 10,
				disabled: false,
				disabled2: 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
					}
				})
				this.$store.dispatch('setPublicObj', '')
			}
		},
		methods: {
			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_name: '物料',
					pscn: '',
					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.dataList = []
				this.pkId = ''
				this.pkObj = {}
				this.disabled = false
				this.disabled2 = false
			},
			handleChange (e) {
				if (e) {
					this.searchList()
				}
			},
			searchList () {
				this.dataList = []
				this.pageNum = 1
				this._selectMaterialByPointCode()
			},
			async _selectMaterialByPointCode () {
				let res = await selectMaterialByPointCode(this.val1)
				this.dataList = res.data
				// this.totalCount = res.totalElements
				// if (res.totalElements > 0) {
				// 	const dataMap = res.data
				// 	this.dataList = this.reload ? dataMap : this.dataList.concat(dataMap)
				// 	this.reload = false
				// } else {
				// 	this.dataList = []
				// }
				// if (this.totalCount == this.dataList.length) {
				// 	this.reload = false
				// 	this.status = 'noMore'
				// }
			},
			onReachBottom () {
				if (this.totalCount > this.dataList.length) {
					this.status = 'loading'
					setTimeout(() => {
						this.pageNum++
						this._selectMaterialByPointCode()
					}, 1000)
				} else { //停止加载
					this.status = 'noMore'
				}
			},
			async handleConfirm() {
				if (!this.val1 || !this.dataList.length) {
					return
				}
				const isConfirmed = await confirmAction("确认操作", "确定要执行此操作吗？")
				if (isConfirmed) {
					this._materialBinding()
				}
			},
			async _materialBinding () {
				this.disabled = true
				try {
					let res = await materialBinding(this.val1, this.dataList)
					if (res.code === '200') {
						this.val1 = ''
						this.dataList = []
						uni.showToast({
							title: res.message,
							icon: 'none'
						})
						this.clearUp()
					} else {
						uni.showToast({
							title: res.message,
							icon: 'none'
						})
					}
					this.disabled = false
				} catch (e) {
					this.disabled = false
				}
			},
			async handleConfirm2() {
				if (!this.val1) {
					return
				}
				const isConfirmed = await confirmAction("确认操作", "确定要执行此操作吗？")
				if (isConfirmed) {
					this._vehicleBinding()
				}
			},
			async _vehicleBinding() {
				this.disabled2 = true
				try {
					let res = await vehicleBinding(this.val1)
					if (res.code === '200') {
						this.val1 = ''
						uni.showToast({
							title: res.message,
							icon: 'none'
						})
						this.clearUp()
					} else {
						uni.showToast({
							title: res.message,
							icon: 'none'
						})
					}
					this.disabled2 = false
				} catch (e) {
					this.disabled2 = false
				}
			}
		}
	}
</script>
<style lang="stylus">
	.checked
		background #ff0
</style>