<template>
	<!-- 添加维修工单 -->
	<view class="add-form-container">
		<!-- <u-form :model="form" ref="form1" label-width="160rpx">
			<u-form-item label="申请主题" prop="name" required>
				<u-input v-model="form.name" placeholder="请输入申请主题" />
			</u-form-item>
		</u-form> -->
		<view class="list">
			<view class="title">
				<span>*</span>申请备件
			</view>
			<view class="item " v-for="(item,index) in form.itemNumbers" :key="index">
				<view class="item-box">
					<view class="spare-title">
						<view class="title-txt">
							{{item.name}}
						</view>
					</view>
					<u-row gutter="16">
						<u-col :span="24">
							<view class="dec">
								库位:{{item.locationNumber}}
							</view>
						</u-col>
						<u-col :span="24">
							<view class="dec">
								数量:{{item.qty}}
							</view>
						</u-col>
						<u-col :span="24">
							<view class="dec">
								维修结果:{{item.result == 'YES'?'完成':'未完成'}}
							</view>
						</u-col>
						<u-col :span="24">
							<view class="dec">
								维修原因:{{item.reasons}}
							</view>
						</u-col>
					</u-row>
				</view>
				<u-icon name="minus-circle" color="#aaaaaa" size="60" @click="delSpareParts(index)"></u-icon>
			</view>
			<view class="add-btn">
				<u-button type="primary" @click="open"><u-icon name="plus-circle" color="#ffffff"
						size="36"></u-icon>添加备件</u-button>
			</view>
		</view>
		<view class="footer">
			<view class="btns">
				<button class="reset" @click="reset">重置</button>
				<button class="sure" @click="submit" :loading='loading' :disabled='loading'>确定</button>
			</view>
			<view style="height: constant(safe-area-inset-bottom); height: env(safe-area-inset-bottom);"></view>
		</view>
		<!-- 添加备件 -->
		<u-popup v-model="isPopupShow" mode="center" border-radius="14">
			<view class="popup-title">添加备件</view>
			<view class="popup">
				<u-form :model="form1" ref="formRef" label-width="200rpx">
					<u-form-item :label="`备件`" prop="itemNumber" required>
						<view class="select" @click="openSingleColumn('itemNumber',form1.itemNumber,sparePartsList)">
							<view class="input" v-if='form1.itemNumber'>
								{{form1.name}}
							</view>
							<view class="placeholder" v-else>
								请选择备件
							</view>
							<u-icon name="arrow-right" color="#aaaaaa" size="28"></u-icon>
						</view>
					</u-form-item>
					<u-form-item label="库位" prop="locationNumber" required v-if="isShow">
						<u-input v-model="form1.locationNumber" placeholder="请输入库位" @blur="blur()"  @confirm='blur()'/>
						<view class="right-button" @click="chickRightButton">
							扫描
						</view>
					</u-form-item>
					<u-form-item label="数量" prop="qty" required>
						<u-input v-model="form1.qty" type="number" placeholder="请输入数量" />
					</u-form-item>
					<u-form-item label="维修结果" prop="reasons" required>
						<u-radio-group v-model="form1.result">
							<u-radio :name="item.value" v-for="(item,index) in result"
								:key="index">{{item.label}}</u-radio>
						</u-radio-group>
					</u-form-item>
					<u-form-item label="维修原因" prop="reasons" required>
						<u-input v-model="form1.reasons" placeholder="请输入维修原因" />
					</u-form-item>
				</u-form>
			</view>
			<view class="popup-footer">
				<view @click="isPopupShow = false">取消</view>
				<view class="sure" @click="addSpare">确认</view>
			</view>
		</u-popup>
		<u-select v-model="singleColumnShow" mode="single-column" :default-value='singleColumnDefaultValue'
			:list="singleColumnList" @confirm="chooseSingleColumn" @cancle='singleColumnShow = false'></u-select>
		<SelectItemList :isShowSelectItem='isShowSelectItem' :singleColumnList='singleColumnList'  @searchItem='searchItem' @chooseItem1='chooseItem1'/>
	</view>
</template>

<script setup lang="ts">
	import {
		onLoad,
	} from '@dcloudio/uni-app'
	import {
		ref,
		getCurrentInstance
	} from 'vue'
	import * as sparePartsApi from "@/api/spareParts"
	import * as sparePartsServiceWorkOrderListApi from "@/api/sparePartsServiceWorkOrderList"
	import * as dictApi from "@/api/dict"
	import * as locationApi from "@/api/location"
	import SelectItemList from "../../components/item/slectItemList.vue"
  import {noPage} from "@/api/spareParts";
	const { proxy } = getCurrentInstance()
	const loading = ref(false)
	const type = ref('')
	// 备件弹窗
	const isPopupShow = ref(false)
	const sparePartsList = ref([])

	const singleColumnShow = ref(false)
	const singleColumnDefaultValue = ref([])
	const singleColumnList = ref([])
	const isShowSelectItem = ref(false)
	const field = ref('')
	const form = ref({
		itemNumbers: []
	})
	const form1 = ref({
		itemNumber: "",
		qty: '',
		result: 'YES',
		reasons: '',
		locationNumber: '',
		areaNumber: ''
	})
	const result = ref([])
	const isShow = ref(false)

	const choosesingleColumnItem = ref()
	const isInAccount = ref()
	const itemNumber = ref()
	const msg = ref('')

	// 触发提交表单
	function submit() {
		// 校验
		if (form.value.itemNumbers == 0) {
			proxy.$modal.showToast('请选择备件')
			return;
		}
		proxy.$modal.confirm('是否添加备件维修工单').then(() => {
			proxy.$modal.loading('加载中')
			loading.value = true
			sparePartsServiceWorkOrderListApi.sparePartsServiceWorkOrderListCreate(form.value).then((
				res) => {
				proxy.$modal.closeLoading()
				if (res.data) {
					proxy.$modal.showToast('添加成功')
					setTimeout(() => {
						proxy.$tab.navigateBack()
						loading.value = false
					}, 1500)
				} else {
					if(res.msg){
						proxy.$modal.showToast(res.msg)
					}else{
						proxy.$modal.showToast('添加失败')
					}
					loading.value = false
				}
			}).catch(() => {
				proxy.$modal.closeLoading()
				loading.value = false
			})
		})
	}
	// 重置
	function reset() {
		form.value = {
			itemNumbers: []
		}
	}
	// 单列模式
	function openSingleColumn(fieldName, val, list) {
		if (fieldName == 'deviceNumber' && form.value.id) return;
		uni.showLoading({
			title: "加载中....",
			mask: true
		});
		singleColumnList.value = list
		field.value = fieldName
		if (val) {
			singleColumnDefaultValue.value = [list.findIndex(item => item.value == val)]
		} else {
			singleColumnDefaultValue.value = []
		}
		isShowSelectItem.value = true
	}
	// 单列模式点击确定之后
	function chooseSingleColumn(e) {
		form1.value[field.value] = e[0].value
		if (field.value == 'itemNumber') {
			choosesingleColumnItem.value = singleColumnList.value.filter(item => item.number == e[0].value)
			form1.value.name = e[0].label
			form1.value.locationNumber = choosesingleColumnItem.value[0].locationNumber
			form1.value.areaNumber = choosesingleColumnItem.value[0].areaNumber
			if (!choosesingleColumnItem.value[0].locationNumber) {
				isShow.value = true
			} else {
				isShow.value = false
				itemNumber.value = ''
			}
		}
		singleColumnShow.value = false
	}
	// 获取备件列表
	async function getServiceSparePartsList() {
		uni.showLoading({
			title: "加载中....",
			mask: true
		});
		await sparePartsApi.noPage({}).then(res => {
			res.data.map(item => {
				item.value = item.number
				item.label = item.name
			})
			sparePartsList.value = res.data
		}).catch(() => { }).finally(()=>{
			uni.hideLoading()
		})
		
	}
	// 扫描设备条码
	function chickRightButton(field) {
		uni.scanCode({
			success: function (res) {
				form1.value.locationNumber = res.result
				getLocation()
			}
		});
	}
	function getLocation() {
		locationApi.getLocation(form1.value.locationNumber).then(res => {
			if (!res.data) {
				msg.value = res.msg ? res.msg : '找不到该库位'
				proxy.$modal.showToast(msg.value)
				
				form1.value.areaNumber =''
				isInAccount.value = ''
				itemNumber.value = ''
				return;
			}
			msg.value = ''
			form1.value.areaNumber = res.data.areaNumber;
			isInAccount.value = res.data.isInAccount
			itemNumber.value = res.data.itemNumber
		}).catch(() => { })
	}
	function blur() {
		if (form1.value.locationNumber) {
			getLocation()
		}
	}
	// 打开弹窗
	function open() {
		form1.value = {
			itemNumber: "",
			qty: '',
			result: 'YES',
			reasons: '',
			locationNumber: '',
			areaNumber: ''
		}
		isPopupShow.value = true
	}
	// 添加配件
	function addSpare() {
		// 校验
		if (!form1.value.itemNumber) {
			proxy.$modal.showToast('请选择备件')
			return;
		}
		if (!form1.value.locationNumber) {
			proxy.$modal.showToast('请扫描库位')
			return;
		}
		if(msg.value){
			proxy.$modal.showToast(msg.value)
			return;
		}
		if (isInAccount.value == 'TRUE') {
			proxy.$modal.showToast('该库位属于帐内库，请选择帐外库')
			return;
		}
		if (form1.value.itemNumber != itemNumber.value) {
			proxy.$modal.showToast('该库位与填写备件不一致')
			return;
		}
		if (!form1.value.qty) {
			proxy.$modal.showToast(`请输入数量`)
			return;
		}
		if (!form1.value.result) {
			proxy.$modal.showToast('请选择维修结果')
			return;
		}
		if (!form1.value.reasons) {
			proxy.$modal.showToast('请输入维修原因')
			return;
		}
		if (form.value.itemNumbers && form.value.itemNumbers.length > 0) {
			let arr = form.value.itemNumbers.filter(item => item.itemNumber == form1.value.itemNumber)
			if (arr && arr.length > 0) {
				proxy.$modal.showToast('该备件已添加')
				return;
			}
		}
		if (form.value.itemNumbers && form.value.itemNumbers.length > 0) {
			let arr1 = form.value.itemNumbers.filter(item => item.locationNumber == form1.value.locationNumber)
			if (arr1 && arr1.length > 0) {
				proxy.$modal.showToast('该库位已经绑定备件')
				return;
			}
		}
		form.value.itemNumbers.push(form1.value)
		isPopupShow.value = false
	}
	// 删除备件
	function delSpareParts(index) {
		form.value.itemNumbers.splice(index, 1)
	}
	
	
	
	async function searchItem(name){
		uni.showLoading({
			title: "加载中....",
			mask: true
		});
		await getSparePartsList(name);
	}
	
	// 获取备件列表
	async function getSparePartsList(name) {
		let param = {
			name:name
		}
		await sparePartsApi.getSparePartsList(param).then(res => {
			res.data.map(item => {
				item.value = item.number
				item.label = item.name
			})
			sparePartsList.value = res.data
			singleColumnList.value = sparePartsList.value
			uni.hideLoading()
		}).catch(() => {
			uni.hideLoading()
		})
		
	}
	
	
	async function chooseItem1(type, form) {
	    if (!form.value.number && type == 1) {
	        proxy.$modal.showToast('请选择备件');
	        return;
	    }
		if (type == 1) {
			uni.showLoading({
				title: "加载中....",
				mask: true
			});
			form1.value['itemNumber'] = form.value.number
			choosesingleColumnItem.value = sparePartsList.value.filter(item => item.number == form.value.number)
			form1.value.name = form.value.name
			form1.value.locationNumber = choosesingleColumnItem.value[0].locationNumber
			form1.value.areaNumber = choosesingleColumnItem.value[0].areaNumber
			if (!choosesingleColumnItem.value[0].locationNumber) {
				isShow.value = true
			} else {
				isShow.value = false
				itemNumber.value = ''
			}
			await getSparePartsList(null);
			isShowSelectItem.value = false;
			uni.hideLoading()
		}else{
			isShowSelectItem.value = false;
			uni.hideLoading()
		}
	}
	
	
	onLoad(async (option) => {
		if (option.type) type.value = option.type;
		result.value = await dictApi.getDict('result')
		await getServiceSparePartsList()
	})
</script>

<style lang="scss" scoped>
	.add-form-container {
		min-height: calc(100vh - 140rpx);
		background: white;
		padding: 0px 0rpx 140rpx;
	}

	.u-form-item {
		padding: 20rpx 30rpx;
	}

	.disabled {
		background: #f5f5f5;
	}

	.footer {
		position: fixed;
		bottom: 0px;
		left: 0px;
		width: 100%;
		z-index: 22;
	}

	.btns {
		display: flex;


		button {
			flex: 1;
		}

		.sure {
			background: #409eff;
			color: white;
			border-radius: 0px;

			&::after {
				border: 1px solid #409eff;
				border-radius: 0px;
			}
		}

		.reset {
			background: #F5F5F5;
			border-radius: 0px;

			&::after {
				border-radius: 0px;
			}
		}
	}

	.right-button {
		background: #409eff;
		color: white;
		padding: 0rpx 30rpx;
		border-radius: 16rpx;
		text-align: center;
		font-size: 28rpx;
	}

	.select {
		display: flex;
		align-items: center;
		height: 72rpx;
		width: 100%;

		.input {
			flex: 1;
			font-size: 28rpx;
			color: #000000;
		}

		.placeholder {
			flex: 1;
			font-size: 28rpx;
			color: rgb(192, 196, 204);

		}
	}

	.title {
		padding: 32rpx 0rpx;
		position: relative;

		span {
			position: absolute;
			left: -16rpx;
			color: #fa3534;
			top: 19px;
		}
	}

	.list {
		padding: 0rpx 30rpx;

		.item {
			display: flex;
			margin-bottom: 20rpx;

			.item-box {
				background: #F5F5F5;
				border-radius: 12rpx;
				flex: 1;
				width: 0rpx;
			}

			.spare-title {
				padding: 20rpx 30rpx;
				border-bottom: 1px solid #e4e4e4;

				.title-txt {
					color: #409eff;
					font-size: 30rpx;
					font-weight: bold;
				}
			}

			.dec {
				color: #9c9c9c;
				padding: 20rpx 30rpx 20rpx;
			}

		}
	}

	.add-btn {
		display: flex;
		justify-content: flex-start;
		align-items: center;
	}

	.popup-title {
		text-align: center;
		font-size: 32rpx;
		font-weight: bold;
		color: #409eff;
		padding: 30rpx 30rpx 0px
	}

	.popup {
		width: 600rpx;
		padding: 30rpx 0rpx 30rpx;

	}

	.popup-footer {
		display: flex;
		border-top: 1px solid #e4e4e4;

		view {
			line-height: 100rpx;
			flex: 1;
			text-align: center;

			&.sure {
				color: #409eff;
			}
		}
	}

	::v-deep .u-checkbox-group {
		display: grid !important;
	}
</style>