<template>
	<view class="page">
		<scroll-view scroll-y="true" class="detail">
			<view class="form-content">
				<uni-forms ref="maintenanceFormRef" labelWidth="140px" :model="mainWorkOrder">
					<!-- 工单名称 -->
					<uni-forms-item class="form-item" :label="$t('workOrder.workOrderName')" name="name"
						:required="false">
						<uni-easyinput style="text-align: right" :inputBorder="false" :clearable="false"
							:disabled="true" :styles="{disableColor:'#fff'}" v-model="mainWorkOrder.name"
							:placeholder="' '" />
					</uni-forms-item>
					<!-- 工单编号 -->
					<uni-forms-item class="form-item" :label="$t('workOrder.workOrderNumber')" name="orderNumber"
						:required="false">
						<uni-easyinput style="text-align: right" :inputBorder="false" :clearable="false"
							:disabled="true" :styles="{disableColor:'#fff'}" v-model="mainWorkOrder.orderNumber"
							:placeholder="' '" />
					</uni-forms-item>
					<!-- 保养类型 -->
					<uni-forms-item class="form-item" :label="$t('maintenanceWorkOrder.maintenanceType')"
						name="outsourcingFlag" :required="false">
						<uni-data-select :styles="{disableColor:'#fff'}" :clear="false" :disabled="true"
							v-model="mainWorkOrder.outsourcingFlag" :localdata="outsourcingFlagRange">
						</uni-data-select>
					</uni-forms-item>

					<!-- 填报人 -->
					<uni-forms-item class="form-item" :label="$t('maintenanceWorkOrder.applicant')" name="applicant"
						:required="false">
						<uni-easyinput style="text-align: right" :inputBorder="false" :clearable="false"
							:disabled="true" :styles="{disableColor:'#fff'}" v-model="mainWorkOrder.applicant"
							:placeholder="' '" />
					</uni-forms-item>

					<!-- 实际保养开始时间 -->
					<uni-forms-item class="form-item" :label="$t('maintenanceWorkOrder.actualMaintenanceStartTime')"
						name="actualStartTime" :required="false">
						<uni-datetime-picker type="datetime" :border="false" :end="dateMax" :placeholder="' '"
							:clear-icon="false" :disabled="true"
							:style="{color: mainWorkOrder.actualStartTime ? '#333' : '#999', 'font-size':mainWorkOrder.actualStartTime ? '14px !important' : 'inherit !important' }"
							v-model="mainWorkOrder.actualStartTime">
						</uni-datetime-picker>

					</uni-forms-item>
					<!-- return-type="timestamp" -->
					<!-- 实际保养结束时间 -->
					<uni-forms-item class="form-item" :label="$t('maintenanceWorkOrder.actualEndTime')"
						name="actualEndTime" :required="false">
						<uni-datetime-picker type="datetime" :border="false" :end="dateMax" :placeholder="' '"
							:clear-icon="false" :disabled="true"
							:style="{color: mainWorkOrder.actualEndTime ? '#333' : '#999', 'font-size':mainWorkOrder.actualEndTime ? '14px !important' : 'inherit !important' }"
							v-model="mainWorkOrder.actualEndTime">
						</uni-datetime-picker>

					</uni-forms-item>

					<!-- 保养费用 -->
					<uni-forms-item class="form-item" :label="$t('maintenanceWorkOrder.maintenanceCost')" name="cost"
						:required="false">
						<uni-easyinput style="text-align: right" :inputBorder="false" :clearable="false"
							:styles="{disableColor:'#fff'}" v-model="mainWorkOrder.cost" :disabled="true" />
					</uni-forms-item>
					<!-- 其他费用 -->
					<uni-forms-item class="form-item" :label="$t('maintenanceWorkOrder.otherCost')" :required="false"
						name="otherCost">
						<uni-easyinput style="text-align: right" :inputBorder="false" :clearable="false"
							:disabled="true" :styles="{disableColor:'#fff'}" v-model="mainWorkOrder.otherCost"
							:placeholder="' '" />
					</uni-forms-item>

					<!-- 备注 -->
					<uni-forms-item class="form-item" :label="$t('operation.remark')" :required="false" name="remark">
						<uni-easyinput style="text-align: right" type="textarea" :autoHeight="true" :inputBorder="false"
							:disabled="true" :clearable="false" :styles="{disableColor:'#fff'}"
							v-model="mainWorkOrder.remark" :placeholder="' '" />
					</uni-forms-item>
				</uni-forms>
				<view class="device-section" v-for="bom in mainWorkOrderBom">
					<!-- 设备编码 -->
					<view class="item-module">
						<view class="item-content flex-row align-center justify-between">
							<view class="item-title">
								<span class="item-title-width">{{$t('device.deviceCode')}}:</span>
							</view>
							<view class="item-title">
								<span>{{bom.deviceCode}}</span>
							</view>
						</view>
						<view class="module-border"> </view>
					</view>
					<!-- 设备名称 -->
					<view class="item-content flex-row align-center justify-between">
						<view class="item-title">
							<span class="item-title-width">{{$t('device.deviceName')}}:</span>
						</view>
						<view class="item-title">
							<span>{{bom.deviceName}}</span>
						</view>
					</view>
					<!-- 累计运行时间 -->
					<view class="item-content flex-row align-center justify-between">
						<view class="item-title">
							<span
								class="item-title-width">{{$t('maintenanceWorkOrder.accumulatedRunningTime')}}(h):</span>
						</view>
						<view class="item-title">
							<span>{{bom.totalRunTime}}</span>
						</view>
					</view>
					<!-- 累计运行里程 -->
					<view class="item-content flex-row align-center justify-between">
						<view class="item-title">
							<span
								class="item-title-width">{{$t('maintenanceWorkOrder.accumulatedRunningMileage')}}(km):</span>
						</view>
						<view class="item-title">
							<span>{{bom.totalMileage}}</span>
						</view>
					</view>
					<!-- 保养项 -->
					<view class="item-content flex-row align-center justify-between">
						<view class="item-title">
							<span class="item-title-width">{{$t('maintenanceWorkOrder.maintenanceItems')}}:</span>
						</view>
						<view class="item-title">
							<span>{{bom.name}}</span>
						</view>
					</view>
					<!-- 物料数量 -->
<!-- 					<view class="item-content flex-row align-center justify-between">
						<view class="item-title">
							<span class="item-title-width">{{$t('workOrder.materialCount')}}:</span>
						</view>
						<view class="item-title">
							<span>{{bom.materialCount}}</span>
						</view>
					</view> -->
					<!-- 操作按钮 -->
					<view class="item-opera flex-row justify-end">
						<button type="primary" :plain="false"
							@click="onMaterialView(bom)">{{$t('workOrder.materialDetails')}}</button>
					</view>
				</view>
			</view>
		</scroll-view>
	</view>
	<!--	<deviceMultiple ref="deviceMultipleRef" @multiple-devide-submit="onChooseDevice" />-->
	<materialsChoose ref="materialsChooseRef" :deviceId="addMateriaItem.id" :materialItem="addMateriaItem"
		@material-submit="materialSubmit" />
	<materials-view ref="materialsViewRef" />

</template>

<script setup>
	import {
		onLoad,
		onReady
	} from '@dcloudio/uni-app'
	import {
		reactive,
		ref,
		onMounted,
		onBeforeUnmount,
		nextTick,
		getCurrentInstance
	} from 'vue';
	import {
		getMaintenanceDetail,
		getWorkOrderBOMs
	} from '@/api/maintenance'
	import {
		getRandomNumber
	} from '@/utils/methods'
	import dayjs from 'dayjs';
	// import deviceMultiple from '@/components/device/multiple.vue'
	import materialsChoose from '@/components/materials/choose.vue'
	import materialsView from '@/components/materials/view.vue'


	// 引用全局变量$t
	const {
		appContext
	} = getCurrentInstance();
	const t = appContext.config.globalProperties.$t;

	const outsourcingFlagRange = ref([{
			value: 0,
			text: t('maintenanceWorkOrder.maintenanceTypeIn')
		},
		{
			value: 1,
			text: t('maintenanceWorkOrder.maintenanceTypeOut')
		},
	])
	// 获取当前时间
	const now = dayjs().format('YYYY-MM-DD HH:mm:ss')
	const dateMax = ref(now)

	const workOrderId = ref()
	const mainWorkOrder = ref({})
	const getDetail = (id) => {
		getMaintenanceDetail({
			id: id
		}).then(res => {
			console.log('getMaintenanceDetail', res.data)
			mainWorkOrder.value = res.data
		})
	}


	// 保养工单明细
	const mainWorkOrderBom = ref([])

	const onDeviceBomList = () => {
		getWorkOrderBOMs({
			workOrderId: workOrderId.value
		}).then(res => {
			console.log('getWorkOrderBOMs', res.data)
			mainWorkOrderBom.value = res.data

		}).catch(err => {

		})
	}

	// 物料选择
	const materialsChooseRef = ref(null)
	const addMateriaItem = ref({})
	const onMaterialChoose = (item) => {
		console.log('onMaterialChoose', item)
		addMateriaItem.value = item
		materialsChooseRef.value.open()
	}
	// 保养工单 - 物料
	const mainWorkOrderMaterials = ref([])
	const materialSubmit = (material) => {
		console.log('material - submit', material)
		// 判断mainWorkOrderMaterials中是否存在相同id的物料，如果存在，则更新数量，如果不存在，则添加
		const index = mainWorkOrderMaterials.value.findIndex(item => item.id === material.id)
		if (index !== -1) {
			mainWorkOrderMaterials.value[index].quantity += material.quantity
		} else {
			mainWorkOrderMaterials.value.push({
				...material,
				id: getRandomNumber(),
				workOrderId: mainWorkOrder.id, // 保养工单id
				bomNodeId: addMateriaItem.value.bomNodeId,
				name: addMateriaItem.value.name,
				code: addMateriaItem.value.code
			})
			// 修改是否选择物料
			mainWorkOrderBom.value.forEach(bom => {
				if (bom.bomNodeId === addMateriaItem.value.bomNodeId) {
					bom.materialSelected = true
				}
			})
		}
		// 计算保养费用
		mainWorkOrder.value.cost = mainWorkOrderMaterials.value.reduce((total, item) => {
			return total + item.quantity * item.unitPrice
		}, 0)

		console.log('mainWorkOrderMaterials', mainWorkOrderMaterials.value)
	}

	const materialsViewRef = ref(null)
	const onMaterialView = (item) => {
		console.log('onMaterialView', item)
		// materialsViewRef.value.openDrawer()
		uni.navigateTo({
			url: '/pages/material/view?workOrderId=' + workOrderId.value + '&bomId=' + item.id +
				'&bomNodeId=' + item.bomNodeId,
		});
	}



	onMounted(() => {
		// 监听子页面提交的事件
		console.log('onMounted')
		// uni.$on('multiple-devide-submit', (data) => {
		// 	console.log('接收到子页面数据:', data);
		// 	selectedDevices.value = data
		// 	onDeviceBomList()
		// });
	})
	onBeforeUnmount(() => {
		// 移除监听
		console.log('onBeforeUnmount')
		// uni.$off('multiple-devide-submit');
	})

	onLoad((option) => {
		console.log('onLoad', option)
		workOrderId.value = option.id
		getDetail(option.id)
		onDeviceBomList()
	})
	onReady(() => {
		// 设置自定义表单校验规则，必须在节点渲染完毕后执行
		// this.$refs.customForm.setRules(this.customRules)
	})
</script>

<style lang="scss" scoped>
	@import "@/style/work-order-detail.scss";

	.detail {
		position: relative;
		height: calc(100%);
	}

	:deep(.is-disabled) {
		color: #333333 !important;
	}
</style>