<template>
	<!-- 添加维修工单 -->
	<view class="add-form-container">
		<u-form :model="form" ref="formRef" label-width="160rpx">
			<u-form-item label="故障描述" prop="describes" required>
				<u-input v-model="form.describes" placeholder="请输入故障描述" />
			</u-form-item>
			<u-form-item label="故障真因" prop="describes" required>
				<u-input v-model="form.describes1" placeholder="请输入故障真因" />
			</u-form-item>
			<u-form-item label="解决措施" prop="describes" required>
				<u-input type='textarea' v-model="form.workOut" placeholder="请输入解决措施" />
			</u-form-item>
			<u-form-item label="维修人员" prop="describes" required>
				<view class="select" @click="openSelecUser">
					<view class="input" v-if='form.maintenances'>
						{{selectFormatCheck(form.maintenances,selecUserList)}}
					</view>
					<view class="placeholder" v-else>
						请选择维修人员
					</view>
					<u-icon name="arrow-right" color="#aaaaaa" size="28"></u-icon>
				</view>
			</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="12">
							<view class="dec">
								<view class="">
									数量:{{item.qty}}
								</view>
							</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="form1Ref" label-width="160rpx">
					<u-form-item :label="`备件`" prop="number" required>
						<view class="select" @click="openSingleColumn('number',form1.number,sparePartsList)">
							<view class="input" v-if='form1.number'>
								{{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="qty" required>
						<u-input v-model="form1.qty" type="number" 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-popup v-model="isShowSelecUser" mode="center" border-radius="14">
			<view class="popup-title">选择维修人员</view>
			<view class="popup">
				<u-checkbox-group @change="checkboxGroupChange">
					<u-checkbox v-model="item.checked" v-for="(item, index) in selecUserList" :key="index"
						:name="item.id">{{item.name}}</u-checkbox>
				</u-checkbox-group>
			</view>
			<view class="popup-footer">
				<view @click="isShowSelecUser = false">取消</view>
				<view class="sure" @click="chooseUser">确认</view>
			</view>
		</u-popup>
		
		<!-- 选择备件 -->
		<!-- <u-popup v-model="isShowSelectItem" mode="center" border-radius="14">
			<view class="popup-title">选择备件</view>
			<view class="popup">
					<u-search placeholder="搜索" v-model="form1.searchName" @change="searchItem" clearabled=false></u-search>
				<view class="list">
					<view class="item" v-for="(item,index) in singleColumnList" :key="index" @click="chooseItem(item)">
						<u-checkbox v-model="item.checked" shape="circle" style="margin-top: 8rpx;"></u-checkbox>
						<view class="right">
							<view class="item-name">
								备件名称1:<span>{{item.name}}</span>
							</view>
							<view class="item-dec">
								备件编码:<span>{{item.number}}</span>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="popup-footer">
				<view @click="chooseItem1(0)">取消</view>
				<view class="sure" @click="chooseItem1(1)">确认</view>
			</view>
		</u-popup> -->
		<SelectItemList :isShowSelectItem=isShowSelectItem :singleColumnList=singleColumnList  @searchItem='searchItem' @chooseItem1='chooseItem1'/>
		<!-- <u-select v-model="singleColumnShow" mode="single-column" :default-value='singleColumnDefaultValue'
			:list="singleColumnList" @confirm="chooseSingleColumn" @cancle='singleColumnShow = false'></u-select> -->
			
	</view>
</template>

<script setup lang="ts">
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		ref,
		getCurrentInstance
	} from 'vue'
	import * as repairOrderApi from "@/api/repairOrder.js"
	import * as sparePartsApi from "@/api/spareParts.js"
	import * as deptApi from "@/api/dept.js"
	import SelectItemList from "../../components/item/slectItemList.vue"

	const { proxy } = getCurrentInstance()

	const loading = ref(false)
	const type = ref('')
	const deviceNumber = ref('')
	const isPopupShow = ref(false)
	const sparePartsList = ref([])

	const singleColumnShow = ref(false)
	const singleColumnDefaultValue = ref([])
	const singleColumnList = ref([])
	const field = ref('')
	const isShowSelectItem = ref(false)
	const selecUserList = ref([])
	const isShowSelecUser = ref(false)
	const form = ref({
		number: '',
		describes: '',
		describes1: '',
		workOut: '',
		maintenances: '',
		itemNumbers: [],
	})
	const form1 = ref({
		number: "",
		name:"",
		qty: 0,
		temporarilyNumber:"",//；临时选中的编码
		temporarilyName:"",//临时选中的名称
		searchName:"",//模糊搜索
	})
	
	const factoryAreaNumber = ref('')
	const chooseUserList = ref([])
	// 触发提交表单
	function submit() {
		// 校验
		if (!form.value.describes) {
			proxy.$modal.showToast('请输入故障描述')
			return;
		}
		if (!form.value.describes1) {
			proxy.$modal.showToast(`请输入故障真因`)
			return;
		}
		if (!form.value.workOut) {
			proxy.$modal.showToast('请输入解决措施')
			return;
		}
		if (!form.value.maintenances) {
			proxy.$modal.showToast('请选择维修人员')
			return;
		}
		if (form.value.id) {
			proxy.$modal.confirm('是否修改维修内容').then(() => {
				proxy.$modal.loading('加载中')
				loading.value = true
				repairOrderApi.repairOrderDetailUpdate(form.value,type.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
				})
			})
		} else {
			proxy.$modal.confirm('是否添加维修内容').then(() => {
				proxy.$modal.loading('加载中')
				loading.value = true
				repairOrderApi.repairOrderDetailCreate(form.value,type.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 chooseItem(item){
		let arr = singleColumnList.value.filter(cur=>cur.number != item.number)
		arr.forEach(item=>{
			item.checked = false
		})
		item.checked = !item.checked
		let arr1 = singleColumnList.value.filter(cur=>cur.number == item.number)
		form1.value.temporarilyNumber = arr1[0].number;
		form1.value.temporarilyName = arr1[0].name;
	}
	
	async function searchItem(name){
		await getSparePartsList(null,name);
	}
	
	async function chooseItem1(type,forms){
		if(!forms.value.number&&type==1){
			proxy.$modal.showToast('请选择备件')
			return
		}
		if(type==1){
			form1.value.number = forms.value.temporarilyNumber
			form1.value.name =forms.value.temporarilyName
		}
		await getSparePartsList(null,null);
		isShowSelectItem.value = false;
	}
	// 重置
	function reset() {
		form.value.describes  = ''
		form.value.describes1  = ''
		form.value.workOut  = ''
		form.value.maintenances  = ''
		form.value.itemNumbers  = []
	}

	// 获取人员列表
	async function getSelecUser() {
		let data = {
			classType: type.value,
			// factoryAreaNumber: factoryAreaNumber.value
		}
		let arr = []
		if (form.value.maintenances) {
			arr = form.value.maintenances.split(',')
		}
		await deptApi.getSelecUser(data).then(res => {
			res.data.forEach(item => {
				item.checked = false
				arr.forEach(cur => {
					if (item.id == cur) {
						item.checked = true
					}
				})
			})
			selecUserList.value = res.data
		}).catch(() => { })
	}
	// 打开人员列表
	function openSelecUser() {
		isShowSelecUser.value = true
	}
	function checkboxGroupChange(e) {
		chooseUserList.value = e
	}
	// 多选选择框回显
	function selectFormatCheck(val, array) {
		const arr = val.split(',').map(Number)
		let str = array.filter(item => arr.includes(item.id)).map(item => item.name).join(',')
		return str
	}
	// 选择人员
	function chooseUser() {
		form.value.maintenances = chooseUserList.value.join(',')
		isShowSelecUser.value = false
	}
	// 单列模式
	function openSingleColumn(fieldName, val, list) {
		if (fieldName == 'deviceNumber' && form.value.id) return;
		singleColumnList.value = list
		field.value = fieldName
		if (val) {
			singleColumnDefaultValue.value = [list.findIndex(item => item.value == val)]
		} else {
			singleColumnDefaultValue.value = []
		}
		form1.value.searchName = "";
		form1.value.temporarilyName = "";
		form1.value.temporarilyNumber = "";
		//singleColumnShow.value = true
		isShowSelectItem.value = true;
		singleColumnList.value = list
	}
	// 单列模式点击确定之后
	function chooseSingleColumn(e) {
		form1.value[field.value] = e[0].value
		if(field.value=='number'){
			form1.value.name = e[0].label
		}
		singleColumnShow.value = false
	}
	// 获取备件列表
	async function getSparePartsList(number,name) {
		number =deviceNumber.value
		let param = {
			number:number,
			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
		}).catch(() => { })
	}
	
	// 打开弹窗
	function open() {
		form1.value = {
			number: "",
			name:'',
			qty: 0
		}
		isPopupShow.value = true
	}
	// 添加配件
	function addSpare() {
		if (!form1.value.number) {
			proxy.$modal.showToast('请选择备件')
			return;
		}
		if (!form1.value.qty || form1.value.qty == 0) {
			proxy.$modal.showToast('请输入数量')
			return;
		}
		if (form.value.itemNumbers && form.value.itemNumbers.length > 0) {
			let arr = form.value.itemNumbers.filter(item => item.number == form1.value.number)
			if (arr && arr.length > 0) {
				proxy.$modal.showToast('该备件已添加')
				return;
			}
		}

		form.value.itemNumbers.push(form1.value)
		isPopupShow.value = false
	}
	// 删除备件
	function delSpareParts(index) {
		form.value.itemNumbers.splice(index, 1)
	}
	onLoad(async (option) => {
		if (option.type) type.value = option.type;
		if (option.deviceNumber) deviceNumber.value = option.deviceNumber;
		if (option.factoryAreaNumber) factoryAreaNumber.value = option.factoryAreaNumber;
		if (option.number) form.value.number = option.number;
		if (option.data && JSON.parse(decodeURIComponent(option.data)) && JSON.parse(decodeURIComponent(option
			.data)).id) {
			form.value = JSON.parse(decodeURIComponent(option.data))
			form.value.itemNumbers = form.value.items
		};
		await getSelecUser()
		await getSparePartsList()
	})
</script>

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


	.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 0px;
		position: relative;

		span {
			position: absolute;
			left: -16rpx;
			color: #fa3534;
			padding-top: 6rpx;
		}
	}

	.list {
		.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 60rpx 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;
	}
	.item-name{
		font-size: 30rpx;
		font-weight: bold;
		padding: 20rpx 0px 0px;
	}
	.item-dec{
		color: #8f8f8f;
	}
</style>