<template>
	<dialog-base ref="baseDialog" title="周转申请">
		<view class="list-container">
			<view><text style="margin: 0 0 0 5rpx;">请选择周转类型</text></view>
			<view class="btn uni-row">
				<view v-for="(item,index) in turnoverType"
					:class="{ 'middle-btn': true, 'active': item.dictValue == curDayworkItem.turnoverType }"
					@click="selectTurnoverType(item)"><text class="label"
						style="font-size: 30rpx;">{{item.dictLabel}}</text></view>
			</view>
			<view class="" style="margin: 0 20rpx 20rpx 0;width: 88%;">
				<uni-section title="请选择下序工段" title-font-size="32rpx" style="margin: 0 0 0 -16rpx;"
					v-if="curDayworkItem.turnoverType == '1'">
					<uni-data-select v-model="curDayworkItem.deptId" :localdata="insideDepts"
						@change="handleChangeInside" :clear="false"
						style="margin: 0 0 0 16rpx;outline: 2rpx solid #999999;border-radius: 10rpx;"></uni-data-select>
				</uni-section>
				<uni-section title="请选择下序工段" title-font-size="32rpx" style="margin: 0 0 0 -16rpx;"
					v-if="curDayworkItem.turnoverType == '2'">
					<uni-data-select v-model="curDayworkItem.deptId" :localdata="outsideDepts"
						@change="handleChangeOutside" :clear="false"
						style="margin: 0 0 0 16rpx;outline: 2rpx solid #999999;border-radius: 10rpx;"></uni-data-select>
				</uni-section>
			</view>
	<view v-if="curDayworkItem.turnoverType != '3'" class="list-title uni-row">
		<text class="label" style="margin: 0 0 0 -24rpx;" >下序是否包装</text><text style="margin-left: 56rpx;" class="label">否</text>
		<switch class="switch" @change="switchChange" :checked="normalStatus" style="transform: scale(0.8);align-items: center;font-size:32rpx ;" color="rgba(103, 195, 55, 1.0)" />
		<text class="label">是</text>
	</view>
	<view class="list-title">
				<text class="label" style="margin: 0 0 0 -308rpx;" >请选择您摆放位置</text>
			</view>
			<view class="turnArea uni-row" v-if="curDayworkItem.turnoverType == '1'">
				<view v-for="(item,index) in turnAreaList" class="btn">
					<view :class="{ 'middle-btn': true, 'active': handleTurnoverDoor(item) }"
						@click="selectTurnoverDoor(item)"><text class="label"
							style="font-size: 30rpx;">{{item.code}}</text></view>
				</view>
			</view>
			<view class="turnArea uni-row" v-if="curDayworkItem.turnoverType == '2'">
				<view v-for="(item,index) in turnoverArea" class="btn">
					<view :class="{ 'middle-btn': true, 'active': handleTurnoverDoor(item) }"
						@click="selectTurnoverDoorOutside(item)"><text class="label"
							style="font-size: 30rpx;">{{item.code}}</text></view>
				</view>
			</view>
			<view class="turnArea uni-row" v-if="curDayworkItem.turnoverType == '3'">
				<view v-for="(item,index) in turnoverArea" class="btn">
					<view :class="{ 'middle-btn': true, 'active': handleTurnoverDoor(item) }"
						@click="selectTurnoverOutsource(item)"><text class="label"
							style="font-size: 30rpx;">{{item.code}}</text></view>
				</view>
			</view>
		</view>
		<view class="add-btn-container uni-row">
			<button type="default" class="btn" @click="handleConfirm">确认</button>
		</view>
	</dialog-base>
</template>

<script setup>
	import {
		ref,
		getCurrentInstance
	} from 'vue'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		getDictInfoByType
	} from '@/api/dict/dict.js'
	import {
		getTurnoverByWorkshop,
		getOutsourceTurnoverByWorkshop
	} from '@/api/business/workshop.js'
	import {
		getDayWorkItemList,
		saveDayWorkItem,
		turnover,
		turnoverOutsource
	} from '@/api/business/dayWorkItem.js'
	import {
		getDeptListInfo
	} from '@/api/dept/dept.js'
	import {
		getTurnoverListByDeptId,
	} from '@/api/business/turnover.js'
	import {
		store
	} from '@/store/index.js'
	import {
		timestampToTime
	} from '@/utils/common.js'

	const baseDialog = ref(null)
	const turnoverDoorChecked = ref([])
	// 创建一个引用来存储最后一次请求的时间戳
	const lastRequestTimestamp = ref(0);
	const turnoverType = ref([])
	const outTurnArea = ref([])
	const turnoverArea = ref([])
	const normalStatus = ref(false)
	const selection = ref([])
	const curDayworkItem = ref({
		turnoverType: 1
	})
	const dayworkInfo = ref(null)
	const deptList = ref([]) // 工段列表
	const insideDepts = ref([]) // 车间内工段
	const outsideDepts = ref([]) // 车间外工段
	const turnAreaList = ref([]) // 周转区列表
	const emit = defineEmits(['reflushDaywork']) // 自定义调用父组件方法

	onLoad(() => {

	})

	function open(data) {
		resetPage();
		dayworkInfo.value = data;
		normalStatus.value = false
		init();
		baseDialog.value.open();
	}

	defineExpose({
		open
	})

	function close() {
		baseDialog.value.close()
		turnAreaList.value = [];
	}

	function resetPage() {
		turnoverDoorChecked.value = []
		turnoverType.value = []
		turnoverArea.value = []
		selection.value = []
		curDayworkItem.value = {
			turnoverType: 1
		}
		deptList.value = []
		insideDepts.value = []
		outsideDepts.value = []
		turnAreaList.value = []
	}
	function switchChange(event) {
		console.log(event.detail.value)
		//是
		if (event.detail.value) {
			normalStatus.value = true
			curDayworkItem.value.isNextPacking = true
		} else {
			//否
			normalStatus.value = false
			curDayworkItem.value.isNextPacking = false
		}
		console.log(event.detail.value, !store.isPreProcess)
		console.log(curDayworkItem.value)
	}

	function init() {
		console.log(dayworkInfo.value)
		getDictInfoByType('daywork_turnover_type').then(res => {
			turnoverType.value = res.data;
			getTurnoverByWorkshop({
				deptId: store.curDeptDetails.deptId
			}).then(res => {
				turnoverArea.value = res.data;
			})
		})
		getOutsourceTurnoverByWorkshop({
			deptCode:'170000'
		}).then(response =>{
			outTurnArea.value = response.data
		})
		getDayWorkItemList({
			dayworkId: dayworkInfo.value.id,
			userId: store.userInfo.userId,
			lotId: dayworkInfo.value.lotId,
			isWasteRecycling: dayworkInfo.value.isWasteRecycling,
			isAmend:dayworkInfo.value.isAmend,
			processStepNumber: dayworkInfo.value.currentProcess.processStepNumber
		}).then(res => {
			curDayworkItem.value = {
				...res.rows[0],
				turnoverType: 1,
				deptId: null
			};
		})
		getDeptListInfo({
			tenantId: store.tenantId,
			productionPlanDetailId: store.planDetails.id,
			lotId: dayworkInfo.value.lotId,
			isWasteRecycling: dayworkInfo.value.isWasteRecycling,
			isAmend: dayworkInfo.value.isAmend
		}).then(res => {
			for (let i = 0; i < res.data.length; i++) {
				deptList.value = res.data;
				console.log(deptList.value)
				if (store.curDeptDetails.workshopId == res.data[i].workshopId) {
					insideDepts.value.push({
						text: res.data[i].deptName,
						value: res.data[i].deptId,
						data: res.data[i]
					})
				} else {
					outsideDepts.value.push({
						text: res.data[i].deptName,
						value: res.data[i].deptId,
						data: res.data[i]
					})
				}
			}
			console.log(insideDepts.value)
			console.log(outsideDepts.value)
		})
	}

	function selectTurnoverType(item) {
		curDayworkItem.value.deptId = null
		curDayworkItem.value.turnoverType = item.dictValue;
		selection.value = []
		normalStatus.value = false
		curDayworkItem.value.isNextPacking = false
	}

	function selectTurnoverDoor(item) {
		console.log(item,"chejiannei")
		// turnoverDoorChecked.value = item;
		// curDayworkItem.value.turnoverArea = item.dictValue;
		let index = selection.value.findIndex(selectedItem => selectedItem === item);
		if (index > -1) {
			selection.value.splice(index, 1);
		} else {
			selection.value.push(item);
		}
	}

	function selectTurnoverDoorOutside(item) {
		console.log(item,"wai")
		selection.value[0] = item;
	}
	 function selectTurnoverOutsource(item) {
		 console.log(item,"waixie")
		 selection.value[0] = item
	 }

	function handleTurnoverDoor(item) {
		return selection.value.includes(item);
	}
	//校验车间内车间外
	function handleValidate(data) {
		console.log(data)
		if (data.turnoverArea == "" || data.deptId == null || selection.value.length == 0) {
			return false;
		} else {
			return true;
		}
	}
	//校验外协
	function handleValidateOutsource(data) {
		console.log(data)
		if (selection.value.length == 0) {
			return false;
		} else {
			return true;
		}
	}

	function handleConfirmOutsource() {
		if (!handleValidateOutsource(curDayworkItem.value)) {
			uni.showToast({
				icon: "none",
				title: '请选择完整信息'
			});
		} else {
			const currentTime = Date.now();
			
			// 检查是否已经过去了 2 秒
			if (currentTime - lastRequestTimestamp.value < 2000) {
				// 如果在 2 秒 内已经有请求发出，那么不执行
				uni.showToast({
					icon: 'none',
					title: `请勿重复点击`,
					duration: 2000
				})
				return;
			}
		lastRequestTimestamp.value = currentTime;
		curDayworkItem.value.id = null;
		curDayworkItem.value.processStepNumber = dayworkInfo.value.currentProcess.processStepNumber
		curDayworkItem.value.startTime = timestampToTime(new Date());
		curDayworkItem.value.endTime = timestampToTime(new Date());
		curDayworkItem.value.technologicalProcessId = dayworkInfo.value.technologicalProcessId;
		curDayworkItem.value.dayworkId = dayworkInfo.value.id;
		curDayworkItem.value.productionPlanDetailId = dayworkInfo.value.productionPlanDetailId;
		curDayworkItem.value.status = '4';
		if (!store.tenantId) {
			curDayworkItem.value.tenantId = store.userInfo.tenantId;
		} else {
			curDayworkItem.value.tenantId = store.tenantId;
		}
		//curDayworkItem.value.turnoverArea = "外协周转";
		curDayworkItem.value.turnoverArea = selection.value.map((item) => {return item.code;}).join('、')
		// 0627 将turnoverId存入dayworkItem，多选将Id进行拼接
		curDayworkItem.value.turnoverId = selection.value.map((item) => {return item.id;}).join('、')
		/**** 此处暂时为硬编码，170000为外协部门编码，根据编码查询信息 ***/
		curDayworkItem.value.deptCode = 170000;
		close();
		turnoverOutsource(curDayworkItem.value).then(res => {
			if (res.code === 200) {
				uni.showToast({
					icon: 'success',
					title: '操作成功'
				});
				emit('reflushDaywork');
			} else {
				uni.showToast({
					icon: 'none',
					title: res.msg,
					duration:2000
				});
				setTimeout(() => {
				 emit('reflushDaywork')
				}, 1000);
			}
		})
		}
	}

	function handleConfirm() {
		if (curDayworkItem.value.turnoverType == '3') {
			handleConfirmOutsource();
		} else {
			const currentTime = Date.now();
				
				// 检查是否已经过去了 2 秒
				if (currentTime - lastRequestTimestamp.value < 2000) {
					// 如果在 2 秒 内已经有请求发出，那么不执行
					uni.showToast({
						icon: 'none',
						title: `请勿重复点击`,
						duration: 2000
					})
					return;
				}
			lastRequestTimestamp.value = currentTime;
			console.log(dayworkInfo.value)
			curDayworkItem.value.id = null;
			curDayworkItem.value.status = '4';
			curDayworkItem.value.processStepNumber = dayworkInfo.value.currentProcess.processStepNumber
			curDayworkItem.value.startTime = timestampToTime(new Date());
			curDayworkItem.value.endTime = timestampToTime(new Date());
			curDayworkItem.value.technologicalProcessId = dayworkInfo.value.technologicalProcessId;
			curDayworkItem.value.dayworkId = dayworkInfo.value.id;
			curDayworkItem.value.productionPlanDetailId = dayworkInfo.value.productionPlanDetailId;
			if (!store.tenantId) {
				curDayworkItem.value.tenantId = store.userInfo.tenantId;
			} else {
				curDayworkItem.value.tenantId = store.tenantId;
			}



			// 过滤出周转位置的数组,并转换成字符串
			const newArray = selection.value.map((item) => {
				if (item.code) {
					return item.code;
				} else if (item.dictLabel) {
					return item.dictLabel;
				} else {
					return null;
				}
			})
			const newIdArray = selection.value.map((item) => {
				if (item.id) {
					return item.id;
				} else {
					return null;
				}
			})
			if (curDayworkItem.value.turnoverType == '1') {
				curDayworkItem.value.place = newArray.join('、');
				//0628将位置id也拼接的方式存下来
				curDayworkItem.value.placeId = newIdArray.join('、');
				curDayworkItem.value.turnoverArea = "车间内周转看place字段";
			} else {
				curDayworkItem.value.turnoverArea = newArray.join('、');
				//0628将位置id也拼接的方式存下来
				curDayworkItem.value.turnoverId = newIdArray.join('、');
			}
			
			// curDayworkItem.value.dayworkId = store.dayworkInfo.id;
			// 设置周转下一个车间名
			for (let i = 0; i < deptList.value.length; i++) {
				if (deptList.value[i].deptId == curDayworkItem.value.deptId) {
					curDayworkItem.value.deptName = deptList.value[i].deptName;
				}
			}
			console.log(curDayworkItem.value);
			// console.log(dayworkInfo.value)
			if (!handleValidate(curDayworkItem.value)) {
				uni.showToast({
					icon: "none",
					title: '请选择完整信息'
				});
			} else {
				curDayworkItem.value.isNextPacking = false
				if(normalStatus.value) {
					curDayworkItem.value.isNextPacking = true
				}
				
				close();
				turnover(curDayworkItem.value).then(res => {
					if (res.code === 200) {
						uni.showToast({
							icon: 'success',
							title: '操作成功'
						});
						emit('reflushDaywork');
					} else {
						console.log("999")
						console.log(res.msg)
						uni.showToast({
							icon: 'none',
							title: res.msg,
							duration:2000
						});
						setTimeout(() => {
						 emit('reflushDaywork')
						}, 1000);
						
					}
				})
			}
			// emit('confirm');
		}


	}

	function handleChangeInside() {
		let deptInfo = deptList.value.find(item=>  item.deptId == curDayworkItem.value.deptId )
		console.log(deptInfo)
		if(deptInfo.isSortPackaging == 1){
			normalStatus.value = true
		}else{
			normalStatus.value = false
		}
		turnAreaList.value = [];
		selection.value = []
		getTurnoverListByDeptId({
			deptId: curDayworkItem.value.deptId,
		}).then(res => {
			for (var i = 0; i < res.data.length; i++) {
				if (res.data[i].status != 1) {
					turnAreaList.value[i] = res.data[i];
				}
			}
		})
	}

	function handleChangeOutside() {
		let deptInfo = deptList.value.find(item=>  item.deptId == curDayworkItem.value.deptId )
		console.log(deptInfo)
		if(deptInfo.isSortPackaging == 1){
			normalStatus.value = true
		}else{
			normalStatus.value = false
		}
	}
</script>

<style lang="scss">
	.dialog-body {
		.list-container {
			width: 100%;

			.list-title {
				margin-top: 24rpx;

				.label {
					font-size: 32rpx;
				}
			}

			.turnArea {
				flex-wrap: wrap;
				height: auto;
				max-height: 200rpx;
				overflow: auto;
			}

			.btn {
				margin-top: 24rpx;

				.middle-btn {
					margin-right: 32rpx;
					align-items: center;
					justify-content: center;
					padding-left: 0;
					height: 80rpx;
					width: 220rpx;
					border-radius: 8rpx;
					background-color: #FFFFFF;
					border: 1px solid #999999;
					background-color: #FFFFFF;

				}

				.label {
					font-size: 24rpx;
					color: #000000;
				}

				.active {
					border-color: #1684fc;
					background-color: rgb(236, 245, 255);

					.label {
						color: #1684fc;
					}
				}
			}
		}

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

			.btn {
				flex: 1;
				background-color: rgb(255, 121, 1);
				color: #FFFFFF;

			}
		}
	}
</style>