<template>
	<view class="equipmentInformationInfoPage">
		<view class="info-max-box">
			<img class="left-img" v-if="newData.imageUrls[0]" :src="baseUrl+newData.imageUrls[0]">
			<img class="left-img" v-if="!newData.imageUrls[0]" :src="imagesUrl('commonality/chemicalsInfoNull.png')">
			<view class="right-box">
				<view>设备分类：{{newData.categoryName}}</view>
				<view>设备名称：{{newData.deviceName}}</view>
				<view>设备编号：{{newData.deviceCode}}</view>
				<view>设备状态：{{newData.deviceStatusName}}</view>
			</view>
		</view>
		<view class="text-max-box">
			<view>类型</view>
			<view>{{newData.deviceType?newData.deviceType:'-'}}</view>
		</view>
		<view class="text-max-box">
			<view>品牌</view>
			<view>{{newData.brand?newData.brand:'-'}}</view>
		</view>
		<view class="text-max-box">
			<view>设备原值(元)</view>
			<view>{{newData.price?newData.price:'-'}}</view>
		</view>
		<view class="text-title-box">参数用途</view>
		<view class="text-max-box">
			<view>设备用途</view>
			<view class="colorA" @click="lookText(1)">查看</view>
		</view>
		<view class="text-max-box">
			<view>技术参数</view>
			<view class="colorA" @click="lookText(2)">查看</view>
		</view>
		<view class="text-max-box">
			<view>备注</view>
			<view class="colorA" @click="lookText(3)">查看</view>
		</view>
		<view class="text-title-box">设备归属</view>
		<view class="text-max-box">
			<view>设备管理员</view>
			<view>{{newData.adminDisplay?newData.adminDisplay:'-'}}</view>
		</view>
		<view class="text-max-box">
			<view>管理部门</view>
			<view>{{newData.manageDeptName?newData.manageDeptName:'-'}}</view>
		</view>
		<view class="text-max-box">
			<view>存放位置</view>
			<view>{{newData.location?newData.location:'-'}}</view>
		</view>
		<view class="text-title-box">厂家产地</view>
		<view class="text-max-box">
			<view>单位</view>
			<view>{{newData.unit?newData.unit:'-'}}</view>
		</view>
		<view class="text-max-box">
			<view>生产厂家</view>
			<view>{{newData.manufacturer?newData.manufacturer:'-'}}</view>
		</view>
		<view class="text-max-box">
			<view>产地</view>
			<view>{{newData.originPlace?newData.originPlace:'-'}}</view>
		</view>
		<view class="bottom-button" @click="onShade()">登记使用信息</view>
		<view class="shade-max-big-box" v-if="shadeType == 1||shadeType == 2||shadeType == 3||shadeType == 4">
			<view class="shade-top-flex" @click="offShade()"></view>
			<view class="shade-big-box">
				<view class="shade-title-box" v-if="shadeType == 1||shadeType == 2||shadeType == 3">登记使用信息</view>
				<view class="shade-title-box" v-if="shadeType == 4">{{shadeDataD.data1}}</view>
				<!-- 登记 -->
				<view class="shade-box" v-if="shadeType == 1">
					<view class="shade-text-box">
						<view>使用人</view>
						<view>{{shadeDataA.data1}}</view>
					</view>
					<view class="shade-text-box">
						<view>使用类型</view>
						<!-- <view>{{shadeDataA.data2}}</view> -->
						<picker @change="pickerChange" :value="pickerIndex" :range="pickerList">
							<view style="width:400rpx;text-align:right;">{{pickerList[pickerIndex]}}</view>
						</picker>
					</view>
					<view class="shade-text-box">
						<view>开机时间</view>
						<view>{{timestampToStr(shadeDataA.data3)}}</view>
					</view>
					<view class="shade-text-box">
						<view>关机时间</view>
						<view>
							<uni-datetime-picker 
							:hide-second="true"
							:start="timeApplication" @change="timePickerChange()" 
							return-type="timestamp" v-model="shadeDataA.data4">{{timestampToStr(shadeDataA.data4)}}</uni-datetime-picker>
						</view>
					</view>
					
					<view class="shade-text-box">
						<view>使用总时长</view>
						<view>{{shadeDataA.data5}}</view>
					</view>
					<view class="shade-button" @click="submitButton(1)">登记使用</view>
				</view>
				<!-- 结束 -->
				<view class="shade-box" v-if="shadeType == 2">
					<view class="shade-text-box">
						<view>使用人</view>
						<view>{{shadeDataB.data1}}</view>
					</view>
					<view class="shade-text-box">
						<view>使用类型</view>
						<view>{{shadeDataB.data2}}</view>
					</view>
					<view class="shade-text-box">
						<view>开机时间</view>
						<view>{{timestampToStr(shadeDataB.data3)}}</view>
					</view>
					<view class="shade-text-box">
						<view>关机时间</view>
						<view>{{timestampToStr(shadeDataB.data4)}}</view>
					</view>
					<view class="shade-text-box">
						<view>使用总时长</view>
						<view>{{shadeDataB.data5}}</view>
					</view>
					<view class="shade-button" @click="submitButton(2)">结束使用</view>
				</view>
				<!-- 查看 -->
				<view class="shade-box-c" v-if="shadeType == 3">
					<view class="shade-text-title">当前设备已被【{{shadeDataC.data1}}】登记使用，</view>
					<view class="shade-text-title">开机时间：{{shadeDataC.data2}}</view>
					<!-- <view class="shade-text-title">如有疑问请联系：{{shadeDataC.data3}}</view> -->
				</view>
				<view class="shade-box" v-if="shadeType == 4">
					<view class="text-box" style="max-height: 500rpx;overflow-y: scroll;">
						{{shadeDataD.data2}}
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mpDeviceDetail,mpDeviceUsageStart,mpDeviceUsageEnd
	} from '@/pages_equipmentUtilization/api/index.js'
	import { config } from '@/api/request/config.js'
	export default {
		props: {
			equipmentId: {},
		},
		data() {
			return {
				shadeType:0,
				baseUrl:config.base_url,
				userId: uni.getStorageSync('userId'),
				newData:{
					imageUrls:[],
					categoryName:'',
					deviceCode:'',
					deviceName:'',
					deviceStatusName:'',
					deviceType:'',
					brand:'',
					price:'',
					adminDisplay:'',
					manageDeptName:'',
					location:'',
					unit:'',
					manufacturer:'',
					originPlace:'',
					purpose:'',
					techParams:'',
					remark:'',
				},
				shadeDataA:{},
				shadeDataB:{
					data1:'',
					data2:'',
					data3:'',
					data4:'',
					data5:'',
				},
				shadeDataC:{
					data1:'',
					data2:'',
					data3:'',
				},
				shadeDataD:{
					data1:'',
					data2:'',
				},
				pickerList:['自用','对外服务'],
				pickerIndex:0,
				timeApplication:null,
			}
		},
		mounted() {
			this.mpDeviceDetail();
		},
		methods: {
			pickerChange(val){
				console.log('val',val.mp.detail.value);
				this.$set(this,'pickerIndex',val.mp.detail.value);
			},
			//获取设备信息
			async mpDeviceDetail() {
				let self = this;
				const {
					data
				} = await mpDeviceDetail({id:this.equipmentId});
				if (data.code == 200) {
					if(!data.data.imageUrls){
						data.data.imageUrls = [];
					}
					this.$set(this,'newData',data.data);
				}
			},
			lookText(type){
				if(type == 1){
					this.$set(this,'shadeDataD',{
						data1:'设备用途',
						data2:this.newData.purpose?this.newData.purpose:'未配置设备用途',
					});
				}else if(type == 2){
					this.$set(this,'shadeDataD',{
						data1:'技术参数',
						data2:this.newData.techParams?this.newData.techParams:'未配置技术参数',
					});
				}else if(type == 3){
					this.$set(this,'shadeDataD',{
						data1:'备注',
						data2:this.newData.remark?this.newData.remark:'未配置备注',
					});
				}
				this.$set(this,'shadeType',4);
			},
			onShade(){
				//判断 登记时1 退订2 已占用3
				if(this.newData.deviceStatus == 1){
					//维护
					uni.showToast({
						title: '设备维护中,如有疑问请联系管理员.',
						icon:"none",
						mask:true,
						duration: 2000
					});
					return
				}else if(this.newData.deviceStatus == 2){
					//报废
					uni.showToast({
						title: '设备已报废,如有疑问请联系管理员.',
						icon:"none",
						mask:true,
						duration: 2000
					});
					return
				}
				if(this.newData.runStatus == 0){
					//无人使用
					const now = new Date();
					now.setSeconds(0, 0);  // 将秒和毫秒都设为0
					const timestamp = now.getTime()
					this.$set(this,'timeApplication',timestamp);
					this.$set(this,'pickerIndex',0);
					this.$set(this,'shadeDataA',{
						data1:uni.getStorageSync('user-name'),
						data2:null,
						data3:this.timeApplication,
						data4:this.timeApplication,
						data5:'0天0小时0分',
					});
					this.$set(this,'shadeType',1);
				}else if(this.newData.runStatus == 1 && this.newData.currentUserId != this.userId){
					//别人使用中
					this.$set(this,'shadeDataC',{
						data1:this.newData.currentUserName,
						data2:this.newData.currentStartTime,
						// data3:this.toTimestamp(this.newData.currentStartTime),
					});
					this.$set(this,'shadeType',3);
				}else if(this.newData.runStatus == 1 && this.newData.currentUserId == this.userId){
					//自己使用中
					const now = new Date();
					now.setSeconds(0, 0);  // 将秒和毫秒都设为0
					const timestamp = now.getTime()
					this.$set(this,'timeApplication',timestamp);
					this.$set(this,'shadeDataB',{
						data1:this.newData.currentUserName,
						data2:this.newData.usageType == 0?'自用':'对外服务',
						data3:this.toTimestamp(this.newData.currentStartTime),
						data4:this.timeApplication,
						data5:this.formatTimeDiff(this.toTimestamp(this.newData.currentStartTime),this.timeApplication),
					});
					this.$set(this,'shadeType',2);
				}
			},
			offShade(){
				this.$set(this,'shadeType',0);
			},
			//时间戳格式化
			timestampToStr(timestamp) {
			  const date = new Date(timestamp); // 传入毫秒级时间戳
			  const year = date.getFullYear();
			  const month = String(date.getMonth() + 1).padStart(2, '0');  // 月份从0开始，需+1
			  const day = String(date.getDate()).padStart(2, '0');
			  const hours = String(date.getHours()).padStart(2, '0');
			  const minutes = String(date.getMinutes()).padStart(2, '0');
			  // 注意：这里没有拼接秒
			  return `${year}-${month}-${day} ${hours}:${minutes}`;
			},
			//时间格式转时间戳
			toTimestamp(dateStr, isUTC = false) {
				// 假设 dateStr 格式为 "YYYY-MM-DD HH:mm:ss"
				const [datePart, timePart] = dateStr.split(' ');
				const [year, month, day] = datePart.split('-').map(Number);
				const [hour, minute, second] = timePart.split(':').map(Number);
				if (isUTC) {
						// 返回 UTC 时间戳
						return Date.UTC(year, month - 1, day, hour, minute, second);
				} else {
						// 返回本地时间戳
						return new Date(year, month - 1, day, hour, minute, second).getTime();
				}
			},
			//开始时间-结束时间-相差时间
			formatTimeDiff(timestamp1, timestamp2) {
			  // 计算绝对差值（毫秒）
			  const diffMs = Math.abs(timestamp1 - timestamp2);
			  // 转换为总分钟数（向下取整）
			  const totalMinutes = Math.floor(diffMs / (1000 * 60));
			  // 计算天、小时、分钟
			  const days = Math.floor(totalMinutes / (60 * 24));
			  const remainingMinutes = totalMinutes % (60 * 24);
			  const hours = Math.floor(remainingMinutes / 60);
			  const minutes = remainingMinutes % 60;
			  // 构建输出字符串
			  const parts = [];
			  if (days > 0) parts.push(days + '天');
			  if (hours > 0) parts.push(hours + '小时');
			  if (minutes > 0 || parts.length === 0) parts.push(minutes + '分'); // 确保至少显示“0分”
			  return parts.join('');
			},
			//登记-结束时间选择
			timePickerChange(){
				if(this.shadeDataA.data4>this.shadeDataA.data3){
					this.$set(this.shadeDataA,'data5',this.formatTimeDiff(this.shadeDataA.data3,this.shadeDataA.data4));
				}else{
					uni.showToast({
						title: '请检查关机时间',
						icon:"none",
						mask:true,
						duration: 2000
					});
				}
				
			},
			//确定按钮
			submitButton(type){
				let self = this;
				if(type == 1){
					if(this.shadeDataA.data4>this.shadeDataA.data3){
						uni.showModal({
							content: '确认提交?',
							cancelColor: "#999",
							confirmColor: "#0183FA",
							success: function(res) {
								if (res.confirm) {
									self.mpDeviceUsageStart()
								} else if (res.cancel) {}
							}
						});
					}else{
						uni.showToast({
							title: '请检查关机时间',
							icon:"none",
							mask:true,
							duration: 2000
						});
					}
				}else if(type == 2){
					uni.showModal({
						content: '确认提交?',
						cancelColor: "#999",
						confirmColor: "#0183FA",
						success: function(res) {
							if (res.confirm) {
								self.mpDeviceUsageEnd()
							} else if (res.cancel) {}
						}
					});
				}
			},
			//登记使用
			async mpDeviceUsageStart() {
				let self = this;
				let obj = {
					deviceId:this.equipmentId,
					usageType:this.pickerList[this.pickerIndex]=='自用'?0:1,
					startTime:this.timestampToStr(this.shadeDataA.data3)+':00',
					expectedEndTime:this.timestampToStr(this.shadeDataA.data4)+':00',
				}
				const {
					data
				} = await mpDeviceUsageStart(obj);
				if (data.code == 200) {
					this.$set(this,'shadeType',0);
					this.mpDeviceDetail();
					uni.showToast({
						mask: true,
						icon: "none",
						position: "center",
						title: data.message,
						duration: 2000
					});
				}
			},
			//结束使用
			async mpDeviceUsageEnd() {
				let self = this;
				let obj = {
					deviceId:this.newData.currentUsageId,
				}
				const {
					data
				} = await mpDeviceUsageEnd(obj);
				if (data.code == 200) {
					this.$set(this,'shadeType',0);
					this.mpDeviceDetail();
					uni.showToast({
						mask: true,
						icon: "none",
						position: "center",
						title: data.message,
						duration: 2000
					});
				}
			},
		},
	}
</script>

<style lang="stylus" scoped>
	.equipmentInformationInfoPage {
		height: 100%;
		flex:1;
		display:flex;
		flex-direction:column;
		background-color: #fff;
		overflow: scroll;
		.info-max-box{
			display: flex;
			.left-img{
				width:200rpx;
				height:200rpx;
				display: inline-block;
				border:1rpx solid #dedede;
				margin:40rpx 20rpx 20rpx 20rpx;
			}
			.right-box{
				flex:1;
				margin:40rpx 20rpx 20rpx 0;
				view{
					width: 480rpx;
					display:block;
					overflow:hidden;
					text-overflow:ellipsis;
					white-space:nowrap;
					margin-bottom:14rpx;
				}
			}
		}
		.text-max-box{
			display: flex;
			border-bottom: 1rpx solid #f2f2f2;
			line-height:80rpx;
			padding: 0 40rpx;
			view:nth-child(1){
				flex:1;
			}
			view:nth-child(2){
				
			}
			.colorA{
				color:#0183FA;
			}
		}
		.text-title-box{
			line-height:80rpx;
			background-color: #f2f2f2;
			padding: 0 30rpx;
		}
		.bottom-button{
			width:300rpx;
			line-height:80rpx;
			text-align: center;
			margin:60rpx auto;
			color:#fff;
			background-color: #0183FA;
			border-radius:6rpx;
		}
		.shade-max-big-box{
			position: absolute;
			top:0;
			left:0;
			width:100%;
			height:100%;
			background-color: rgba(0,0,0,0.3)
			display: flex;
			flex-direction: column;
			.shade-top-flex{
				flex:1;
			}
			.shade-big-box{
				background-color: #fff;
				.shade-title-box{
					font-weight:900;
					padding-right:20rpx;
					width:300rpx;
					border-bottom-right-radius: 40rpx
					background-color: #0183FA;
					color:#fff;
					text-align: center;
					line-height:60rpx;
				}
				.shade-box{
					padding:20rpx 0 100rpx;
					.shade-text-box{
						display: flex;
						border-bottom:1rpx solid #f2f2f2;
						line-height:80rpx;
						padding:0 30rpx;
						view:nth-child(1){
							flex:1;
						}
						view:nth-child(1){
							flex:3;
						}
					}
					.shade-button{
						width:300rpx;
						line-height:80rpx;
						text-align: center;
						background-color: #0183FA;
						border-radius:8rpx;
						color:#fff;
						margin:40rpx auto 0;
					}
					.text-box{
						padding:60rpx 40rpx 200rpx;
					}
				}
				.shade-box-c{
					padding:120rpx 0 200rpx;
					.shade-text-title{
						text-align-last: center;
						line-height: 60rpx;
					}
				}
			}
		}
	}
</style>