<template>
	<dialog-base ref="baseDialog" title="请选择">
		<!-- 		<view class="equipment-container uni-row ">
			<view v-for="(item, index) in equipments" :class="{'item':true,'selected': isSelected(item)}" :key="index"
				@click="handleSelection(item)"><text class="label">{{item['equipmentDetailCode']}}</text></view>
		</view> -->
		<view v-if="showProcessList">
			<uni-section title="工序" type="line">
				<uni-data-select v-model="selectedProcess" :localdata="processList" :clear="false"
					@change="handleProcessChange"></uni-data-select>
			</uni-section>
		</view>
		<view>
			<uni-section title="设备" type="line">
				<uni-data-select v-model="selectedEquipment" :localdata="equipmentList" :clear="false"
					@change="handleEquipmentChange"></uni-data-select>
			</uni-section>
		</view>
<!-- 		<view class="switch uni-row">
			<text class="label">是否邀请协作者</text>
			<view class="uni-row" style="align-items: center;">
				<text>否</text>
				<switch class="switch" @change="switchChange" />
				<text>是</text>
			</view>
		</view>
		<view class="userList" v-if="flag">
			<uni-easyinput class="uni-mt-5" v-model="userName" placeholder="请输入协作者编号"
				@input="debounce(handleSearchUserName,500)" @blur="handleBlur"></uni-easyinput>

			<view class="uni-row showUser">
				<view v-for="(item,index) in userList">
					<view class="user" @click="handleClickUserName(item)">{{item.nickName}}</view>
				</view>
			</view>
		</view>
		<view class="uni-row selectedUserList">
			<view class="selectedUser uni-row" v-for="(item,index) in selectedUserList">
				<view>{{item.nickName}}</view>
				<view v-if="selectedUserList.length > 0" @click="handleRemoveUserName(item)">×</view>
			</view>
		</view> -->


		<view class="add-btn-container uni-row">
			<button type="primary" class="btn" @click="handleStart">开始</button>
		</view>
	</dialog-base>
</template>

<script setup>
	import {
		ref
	} from 'vue'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		getProcessList
	} from '@/api/business/deptProcess.js'
	import {
		getUserequipmentList
	} from '@/api/business/userEquipment/userEquipment.js'
	import {
		getUserInfo
	} from '@/api/login/index.js'
	import {
		saveDayWorkItem,
		getDayWorkItemList
	} from '@/api/business/dayWorkItem.js'
	import {
		store
	} from '@/store/index.js'
	import {
		getEquipmentByUidAndDid
	} from '@/api/resourceGroup/resourceGroupDetail.js'
	import {
		timestampToTime,
		debounce
	} from '@/utils/common.js'
	import {
		getUserByLikeUsername
	} from '@/api/sys/user.js'

	const baseDialog = ref(null)
	const equipments = ref([]) // 接收设备列表信息
	const equipmentList = ref([])
	const emit = defineEmits(['handleAddDayWorkItem'])
	const userId = ref(null)
	const firstItem = ref(null);
	const sendReqParam = ref({})
	const processList = ref([])
	const selectedProcess = ref(null)
	const selectedEquipment = ref(null)
	const flag = ref(false)
	const userName = ref(null)
	const userList = ref([])
	const selectedUserList = ref([])
	const showProcessList = ref(true)


	onLoad(() => {
		userId.value = store.userInfo.userId || "";
	})

	function resetPage() {
		flag.value = false;
		userName.value = null;
		userList.value = [];
		equipmentList.value = [];
		selectedEquipment.value = null;
		selectedUserList.value = []; 
		selectedProcess.value = null;
		processList.value = [];
		showProcessList.value = true;	
	}

	function init() {
		getProcessList({
			// tenantId: store.tenantId,
			deptId: store.curDeptDetails.deptId,
			dayworkId: store.dayworkInfo.id
		}).then(res => {
			console.log(res)
			if (res.code == 200) {
				//过滤出工序交集store.dayworkInfo.processSequence
				let filteredData = store.dayworkInfo.processSequence.filter((item1) =>
					res.data.some((item2) => item2.processCode === item1.processCode)
				);
				for (let i = 0; i < filteredData.length; i++) {
					processList.value[i] = {
						text: filteredData[i].processAlias,
						value: filteredData[i].technologicalProcessDetailId,
						processId: filterData[i].id
					}
				}
				console.log(processList.value)
				selectedProcess.value = filteredData[0].technologicalProcessDetailId;
				isDefaultItem(firstItem.value);
			} 
		})
		
		// Promise.all([getEquipmentByUidAndDid(store.planDetails.id), getDayWorkItemList({
		// 		// userId: store.userInfo.userId,
		// 		// dayworkId: store.dayworkInfo.id,
		// 		status: 1
		// 	})])
		// 	.then(([equipmentRes, response]) => {
		// 		console.log(equipmentRes)
		// 		console.log(response.rows)
		// 		if (equipmentRes.code == 200 && response.code == 200) {
		// 			let equipmentListData = equipmentRes.rows.filter((equipment) => {
		// 				return !response.rows.some((item) => item.equipmentDetailId == equipment.commonId);
		// 			});
		// 			equipmentList.value = equipmentListData.map((equipment) => {
		// 				return {
		// 					text: equipment.commonCode,
		// 					value: equipment
		// 				}
		// 			});
		// 			selectedEquipment.value = equipmentListData.length > 0 ? equipmentListData[0] : null;
		// 		}
		// 		baseDialog.value.open()
		// 	});
		getEquipmentByUidAndDid(store.planDetails.id,store.curDeptDetails.deptId).then(equipmentRes => {
			if(equipmentRes.code == 200){
				for (var i = 0; i < equipmentRes.rows.length; i++) {
					equipmentList.value[i] = {
						text: equipmentRes.rows[i].commonCode,
						value: equipmentRes.rows[i]
					}
				}
				selectedEquipment.value = equipmentRes.rows.length > 0 ? equipmentRes.rows[0] : null;
			}
			baseDialog.value.open()
		})
	}

	function open(data) {
		resetPage()
		firstItem.value = data;
		userName.value = null;
		userList.value = [];
		init();
	}
	
	function isDefaultItem(item){
		if(item){
			showProcessList.value = false;	
			selectedProcess.value = null;
		}
	}

	function close() {
		baseDialog.value.close()
	}

	defineExpose({
		open
	})

	function handleProcessChange() {

	}

	function handleEquipmentChange() {

	}

	function handleSearchUserName() {
		if (userName.value) {
			getUserByLikeUsername(userName.value).then(res => {
				if (res.code == 200) {
					userList.value = res.data;
				}
			})
		}
	}

	function handleClickUserName(item) {
		selectedUserList.value.push(item);
		userList.value = [];
	}

	function handleBlur() {
		setTimeout(function() {
			userList.value = [];
		}, 200)
	}

	function handleRemoveUserName(item) {
		selectedUserList.value.splice(selectedUserList.value.indexOf(item), 1);
	}

	function switchChange(e) {
		flag.value = e.detail.value;
	}

	function handleStart() {
		uni.showModal({
			title: "提示",
			content: "确认开始新的报工吗",
			success: function(res) {
				if (res.confirm) {
					handleDoStart();
				} else if (res.cancel) {
					close();
				}
			}
		})

	}

	function handleDoStart() {
		// if (!selectedProcess.value || !selectedEquipment.value) {
		// 	uni.showToast({
		// 		icon: "none",
		// 		title: "未选择工序或设备"
		// 	})
		// 	selectedProcess.value = null;
		// 	selectedEquipment.value = null;
		// 	return;
		// }
		close();
		if (firstItem.value) {
			sendReqParam.value = {
				...firstItem.value,
				/* 20240408 前版本
				processId: selectedProcess.value,
				*/
				technologicalProcessDetailId: selectedProcess.value,
				processId: processList.value.findIndex(v => v.value === selectedProcess.value) >= 0 ? processList.value.find(v => v.value === selectedProcess.value).processId : null,
				equipmentDetailId: selectedEquipment.value.commonId,
				equipmentDetailCode: selectedEquipment.value.commonCode,
				startTime: timestampToTime(new Date()),
				status: 1,
				collaborationList: selectedUserList.value
			};
			console.log(sendReqParam.value)
			emit('handleAddDayWorkItem', sendReqParam.value);
		} else {
			emit('handleAddDayWorkItem', {
				/* 20240408 前版本
				processId: selectedProcess.value,
				*/
				technologicalProcessDetailId: selectedProcess.value,
				processId: processList.value.findIndex(v => v.value === selectedProcess.value) >= 0 ? processList.value.find(v => v.value === selectedProcess.value).processId : null,
				equipmentDetailId: selectedEquipment.value.commonId,
				equipmentDetailCode: selectedEquipment.value.commonCode,
				collaborationList: selectedUserList.value
			});
		}
	}
</script>

<style lang="scss">
	.dialog-body {
		.equipment-container {
			height: 300rpx;
			overflow: auto;
			flex-wrap: wrap;
			justify-content: flex-start;
			margin: 24rpx 0 0 7%;

			.item {
				width: 236rpx;
				height: 60rpx;
				text-align: center;
				line-height: 60rpx;
				border-radius: 6rpx;
				margin: 16rpx;
				flex: 0 0 40%;
				border: 1px solid #000000;
			}

			.selected {
				background-color: #1684fc;
				color: #FFF;
			}
		}

		.add-btn-container {
			margin-top: 32rpx;

			.btn {
				flex: 1;
			}
		}

		.switch {
			font-size: 26rpx;
			align-items: center;
			justify-content: space-between;
			margin: 16rpx;
		}

		.userList {
			border: 1rpx solid #1684fc;
			border-radius: 8rpx;
			max-height: 300rpx;
			overflow: auto;
			width: 100%;

			.showUser {
				justify-content: flex-start;
				flex-wrap: wrap;

				.user {
					border: 1rpx solid #999;
					border-radius: 8rpx;
					width: 150rpx;
					height: 50rpx;
					text-align: center;
					line-height: 50rpx;
					margin: 10rpx;
					overflow: auto;
				}
			}
		}

		.selectedUserList {
			width: 100%;
			justify-content: flex-start;
			flex-wrap: wrap;

			.selectedUser {
				border: 1rpx solid #999;
				border-radius: 8rpx;
				width: 150rpx;
				height: 50rpx;
				text-align: center;
				line-height: 50rpx;
				margin: 20rpx 20rpx 0 0;
				justify-content: space-around;

			}
		}
	}
</style>