
<template>
  <view class="container"> 
  
    <!-- 车牌号输入区域 -->
    <view class="section">
      <view class="input-group">
        <text class="label">车牌号</text>
        <view class="input-container">
          <input
            v-model="licensePlate"
            class="input-field"
            placeholder="请输入车牌号"
            maxlength="8"
            @input="onLicenseInput"
          />
          <view class="scan-btn" @click="scanLicense">
            <uni-icons type="scan" size="20" color="#007AFF"></uni-icons>
          </view>
        </view>
        <!-- <text class="hint">例如：京A12345</text> -->
      </view>
    </view>

    <!-- 配送单扫描区域 -->
    <view class="section">
      <view class="scan-area" @click="scanDeliveryOrder">
        <view class="scan-icon">
          <uni-icons type="scan" size="40" color="#007AFF"></uni-icons>
        </view>
        <text class="scan-title">扫描配送单二维码</text>
        <text class="scan-desc">请将摄像头对准配送单二维码</text>
      </view>

      <!-- 配送单详情区域 -->
      <view v-if="deliveryOrderInfo" class="order-details">
        <view class="detail-header">
          <text class="detail-title">配送单详情</text>
        </view>
        <view class="detail-item">
          <text class="item-label">配送单号：</text>
          <text class="item-value">{{ deliveryOrderInfo.orderNumber }}</text>
        </view>
        <view class="detail-item">
          <text class="item-label">配送地址：</text>
          <text class="item-value">{{ deliveryOrderInfo.deliveryAddress }}</text>
        </view>
        <view class="detail-item">
          <text class="item-label">预计送达：</text>
          <text class="item-value">{{ deliveryOrderInfo.estimatedTime }}</text>
        </view>

        <!-- 托盘清单 -->
        <!-- <view class="list-section">
          <text class="list-title">托盘清单</text>
          <view v-for="(item, index) in deliveryOrderInfo.palletList" :key="index" class="list-item">
            <text class="item-text">{{ item.palletNumber }} - {{ item.materialType }} (数量：{{ item.quantity }})</text>
          </view>
        </view> -->

        <!-- 散装管件清单 -->
        <view class="list-section">
          <text class="list-title">散装管件清单</text>
          <view v-for="(item, index) in deliveryOrderInfo.looseMaterials" :key="index" class="list-item">
            <text class="item-text">{{ item.name }} - {{ item.quantity }}{{ item.specification }} </text>
          </view>
        </view>
      </view>
    </view>

    <!-- 托盘管理区域 -->
    <view class="section">
		
		<view class="section-header">
		  <text class="section-title">已添加工装托盘</text>
		  <text class="section-count">({{ palletList.length }})</text>
		</view>

		<uni-collapse  v-if="palletList.length > 0" class="pallet-list" :border="true">
			<uni-collapse-item titleBorder="none" v-for="(pallet, index) in palletList" :key="index" :open="pallet.isOpen" class="pallet-card">
				<template v-slot:title>
					<view class="pallet-info">
					  <text class="pallet-number" @click="openinfo(pallet.palletNo)">{{ pallet.palletNo }}</text>
					  <text class="pallet-status" :class="'status-'+pallet.status">
					    {{ retType(pallet.status,'1')}}
					  </text>
					  <uni-icons type="closeempty" size="16" color="#ff0000"></uni-icons>
					</view>
				</template>
				<UploadzcFile class="upload"
				  @picIds="palletpics($event,index)"
				  :deletable="true"
				  :count="3"
				  :sourceType="sourceType"
				  :width="100"
				  :height="100"
				  :fileidList="pallet.imgs"
				>
				</UploadzcFile>
			</uni-collapse-item>
		</uni-collapse>
      
      <view class="add-pallet-btn" @click="scanPallet">
        <uni-icons type="plusempty" size="20" color="#fff"></uni-icons>
        <text class="btn-text">扫描添加托盘</text>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-actions">
      <!-- <button class="action-btn continue-btn" @click="continueScan">继续扫描</button> -->
      <button class="action-btn complete-btn" @click="finishLoading">完成装车</button>
    </view>
	
	<!-- 查看托盘详情 -->
	<u-popup v-model="show" mode="center" borderRadius="20" closeable @close="close">
		<scroll-view class="new-data-box" scroll-y>
			<uni-list v-if="palletinfo">
				<uni-list-item :ellipsis="1" v-for="(value, key) in palletinfo" :key="key" :title="palletitem[key]" :rightText="value"></uni-list-item>
			</uni-list>
		</scroll-view>
	</u-popup>
	
	<!-- 提示窗示例 -->
	<uni-popup ref="alertDialog" type="dialog">
		<uni-popup-dialog :type="msgType" cancelText="关闭" confirmText="确定" title="消息" :content="messageText"></uni-popup-dialog>
	</uni-popup>
	
  </view>
</template>


<script>
import utils from "@/common/utils.js";
import tkiTree from "@/components/areaTree/Linktree.vue";
import UploadzcFile from "@/components/UploadzcFile.vue";
export default {
	components: {
	  tkiTree,
	  UploadzcFile
	},
	data() {
		return {
			sourceType:['album', 'camera'], // 选择图片的来源，album-从相册选图，camera-使用相机，默认二者都有（默认['album', 'camera']）
			licensePlate:'',// 车牌号
			show: false,
			messageText:"",
			msgType:"info",//success error warn info
			deliveryOrderInfo:{
			  orderNumber: '',
			  deliveryAddress: '',
			  estimatedTime: '',
			  palletList: [
				  {
					  palletNumber:'托盘1',
					  materialType:'材料类型1',
					  quantity:'10'
				  }
			  ],
			  looseMaterials: [
				  {
					  name:'物料1',
					  specification:'箱',
					  quantity:'5',
				  }
			  ] 
			}, // 配送单信息
			// 托盘列表
			palletList:[
				{
					palletNo:"TP001",
					status:"zp", // 字典bmlb=’TPZT;闲置/装盘/配送/周转/接收/卸盘
					imgs:[],
					imgurls:'',
					isOpen:true,
				},
			], 
			palletinfo:{
				"palletNo":"TP001",
				"project":"",
				"instno":"",
				"dwgno":"",
				"section":"",
				"assemcode":"",
				"spec":"",
				"grd":"",
				"qty":"",
				"weight":"",
				"treatment":"",
				"paintcode":"",
				"modifyType":"",
				"modifyKh":"",
				"modifyDwgno":"",
				"modifyDate":"",
				"status":"",
				"statusDate":"",
				"manuDept":"",
				"treatDept":"",
				"deliverDept":"",
				"deliveryId":"",
				"deliveryNo":"",
				"deliveryCar":"",
				"deliveryDate":"",
				"deliveryRemark":"",
				"requireRate":"",
				"requireDepartCode":"",
				"requireAddress":"",
				"requireName":"",
				"requirePhone":"",
				"receiveDate":"",
				"receiveName":"",
				"receiveRemark":""
			},
			palletitem:{
				project:"工程编号",
				instno:"安装托盘表号",
				dwgno:"制作图号",
				section:"分段号",
				assemcode:"部件代号",
				spec:"规格",
				grd:"材质",
				qty:"数量",
				weight:"重量",
				treatment:"表面处理",
				paintcode:"涂装代码",
				modifyType:"修改类型",
				modifyKh:"修改卡号",
				modifyDwgno:"修改通知单号",
				modifyDate:"修改日期",
				status:"生产状态", // status
				statusDate:"状态日期",
				manuDept:"制作单位",
				treatDept:"处理单位",
				deliverDept:"配送单位",
				palletNo:"工装托盘编号",
				deliveryId:"工装托盘转运记录ID",
				deliveryNo:"配送单号",
				deliveryCar:"配送车辆",
				deliveryDate:"配送日期",
				deliveryRemark:"配送备注",
				requireRate:"需求日期",
				requireDepartCode:"需求单位代码",
				requireAddress:"配送地址",
				requireName:"接收人员",
				requirePhone:"接收人员电话",
				receiveDate:"实际接收日期",
				receiveName:"实际接收人员",
				receiveRemark:"实际接收备注"
			},
			// 闲置/装盘/配送/周转/接收/卸盘
			status:[
				{
					key:"xz",
					value:"闲置",
				},
				{
					key:"zp",
					value:"装盘",
				},
				{
					key:"ps",
					value:"配送",
				},
				{
					key:"zz",
					value:"周转",
				},
				{
					key:"js",
					value:"接收",
				},
				{
					key:"xp",
					value:"卸盘",
				}
			],
			itemList:{},
			
		};
	},
	onLoad(options) {
		// 默认日期
		this.itemList.psrq = this.getDay(0);
		// var user= JSON.parse(uni.getStorageSync("user"));
		// var yhms=user.yhms?user.yhms:"";
		// this.itemList.psry = yhms;
		// 获取操作数据
		// this.getTypes();
	},
	onReady() {
		// this.$refs.uForm.setRules(this.rules);
	},
	methods: {
		async openinfo(palletNo){
			
			// 测试打开
			this.open();
			
			// // 托盘详情
			// const {data: res} = await uni.$http.get('/getPallet',{palletNo:palletNo});
			// if(res.success){
			// 	if(res.data){
			// 		this.palletinfo=res.data;
			// 		this.$forceUpdate();
			// 		this.open();
			// 	}
			// 	else{
			// 		this.messageText = "托盘详情获取失败";
			// 		this.$forceUpdate();
			// 		this.dialogToggle("warn");
			// 	}
			// }
			// else{
			// 	this.messageText = "托盘详情获取异常";
			// 	this.$forceUpdate();
			// 	this.dialogToggle("error");
			// }
		},
		dialogToggle(type) {
			this.msgType = type
			this.$refs.alertDialog.open()
		},
		close() {
			this.show = false;
		},
		open() {
			this.show = true;
		},
		// 托盘照片
		palletpics(val,index) {
			console.log(val,index);
			this.palletList[index].imgurls=val.join(",");
			this.$forceUpdate();
			console.log(this.palletList);
		},
		// 折叠
		change(e) {
			console.log(e);
		},
		// 处理完成
		handleComplete(){
		  console.log('完成装车');
		},
		// 车牌号输入处理
		onLicenseInput(e){
		  // 实时校验车牌格式
		  const value = e.detail.value;
		  if (value && !/^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-Z0-9]{4,5}[A-Z0-9挂学警港澳]$/.test(value)) {
		    console.log('车牌格式不正确');
		  }
		},
		// 扫描车牌
		scanLicense(){
		  uni.showModal({
		    title: '提示',
		    content: '模拟扫描车牌',
		    success: (res) => {
		      if (res.confirm) {
		        licensePlate.value = '京A12345';
		      }
		    },
		  });
		},
		// 扫描配送单
		scanDeliveryOrder(){
		  uni.showModal({
		    title: '提示',
		    content: '模拟扫描配送单二维码',
		    success: (res) => {
		      if (res.confirm) {
		        deliveryOrderInfo.value = {
		          orderNumber: 'DD20231201001',
		          deliveryAddress: '北京市朝阳区某某仓库',
		          estimatedTime: '2023-12-01 15:00',
		          palletList: [
		            { palletNumber: 'TP001', materialType: '五金工具', quantity: 5 },
		            { palletNumber: 'TP002', materialType: '建筑材料', quantity: 3 },
		          ],
		          looseMaterials: [
		            { name: '螺丝刀', specification: '十字型', quantity: 10 },
		            { name: '扳手', specification: '12mm', quantity: 5 },
		          ],
		        };
		      }
		    },
		  });
		},
		// 扫描托盘
		scanPallet(){
			var that = this;
			uni.showModal({
			  title: '提示',
			  content: '模拟扫描托盘二维码',
			  success: (res) => {
			    if (res.confirm) {
			      const newPallet = {
			        palletNo: `TP${String(that.palletList.length + 1).padStart(3, '0')}`,
			        status: 'zp',
					imgs:[],
					imgurls:'',
					isOpen:true,
			      };
			      that.palletList.push(newPallet); 
				  this.$forceUpdate();
			    }
			  },
			});
		},
		// 继续扫描
		continueScan(){
		  console.log('继续扫描');
		},
		// 完成装车
		finishLoading(){
		  console.log('完成装车');
		},
		
		getDay(day){
			var today = new Date();
			var targetday_milliseconds=today.getTime() + 1000*60*60*24*day;
			today.setTime(targetday_milliseconds); //注意，这行是关键代码
			var tYear = today.getFullYear();
			var tMonth = today.getMonth();
			tMonth = this.doHandleMonth(tMonth + 1);
			var tDate = today.getDate();
			tDate = this.doHandleMonth(tDate);
			return tYear+"/"+tMonth+"/"+tDate;
		},
		doHandleMonth(month) {
			var m = month;
			if (month.toString().length == 1) {
			  m = "0" + month;
			}
			return m;
		},
		showgsmld() {
			// 选择转运去向
		  this.$refs.gsmldtree._show();
		},
		gsmldtreeConfirm(val) {
			// 转运去向
			if (val && val.length > 0) {
				this.itemList.bm = val[val.length - 1].bm;
				this.itemList.psdd = val[val.length - 1].bm;
				this.itemList.bmsm = val[val.length - 1].bmsm;
			}
			else{
				this.itemList.bm = "";
				this.itemList.psdd = "";
				this.itemList.bmsm = "";
			}
			this.$forceUpdate();
			this.$refs.uForm.validate();
		},
		// 转运日期
		timeConfirm0(e) {
			let selectTime=`${e.year}/${e.month}/${e.day}`;
			this.itemList.psrq = selectTime;
			this.$forceUpdate();
			this.$refs.uForm.validate();
		},
		del(index){
			this.itemList.tpbhList.splice(index,1);
			this.$forceUpdate();
		},
		saoma(){
			var _that=this,rmbm="";
			// #ifdef H5
			// 去接收添加
			rmbm="38393939393";
			_that.addCode(rmbm);
			// #endif
			
			// #ifdef APP-PLUS
			// 允许从相机和相册扫码
			//qrCode,barCode
			uni.scanCode({
				scanType: ['qrCode', 'barCode'],
				success: function(res) {
					console.log('条码类型：' + res.scanType);
					console.log('条码内容：' + res.result);
					// 扫码接收添加
					rmbm=res.result;
					console.log(rmbm);
					if(rmbm){
						_that.addCode(rmbm);
					}
					else{
						_that.$refs.uToast.show({
						  title: "扫码失败，请重试！",
						  type: "warning",
						  duration: 2000,
						});
					}
				}
			});
			// #endif
		},
		addCode(qrcode){
			var ifhave=false;
			this.itemList.tpbhList.forEach(cell=>{
				if(qrcode==cell){
					ifhave=true;
					return;
				}
			});
			if(ifhave){
				this.$refs.uToast.show({
				  title: "条码已存在，请重新扫码！",
				  type: "warning",
				  duration: 2000,
				});
			}
			else{
				this.itemList.tpbhList.push(qrcode);
				this.$forceUpdate();
			}
		},
		save() {
			console.log(this.itemList)
			this.isSubmit = true;
			this.subtext="提交中..";
			this.$refs.uForm.validate((valid) => {
				if (valid) {
					if(this.itemList.tpbhList.length<1){
						this.$refs.uToast.show({
							title: "请扫码添加工装托盘！",
							type: "warning",
							duration: 2000,
						});
						this.isSubmit = false;
						this.subtext="提交中..";
						return false;
					}
					// 添加
					this.adddo();
			    }
				else {
					this.isSubmit = false;
					this.subtext="提交中..";
					this.$refs.uToast.show({
						title: "请填写完数据后再提交！",
						type: "warning",
						duration: 2000,
					});
				}
			});
		},
		async adddo(){
			uni.showLoading({
				title: '提交中...'
			});
			const {data: res} = await uni.$http.post('/api/gjPstpsyjlb/tpbsAdd',this.itemList);
			if(res.success){
				this.subtext="提交完成";
				this.$refs.uToast.show({
				  title: "工装托盘转运新增成功！",
				  type: "success",
				  duration: 2000,
				});
				setTimeout(() => {
				  uni.navigateBack({
				    //返回
				    delta: 1,
				  });
				}, 3000);
			}
			else{
				this.subtext="提交失败";
				this.isSubmit = false;
				this.$refs.uToast.show({
				  title: res.message? res.message:"工装托盘转运新增失败！",
				  type: "warning",
				  duration: 3000,
				});
			}
		},
		async getTypes() {
			//获取数据字典
			var _this = this;
			// 转运去向
			const {data: res} = await uni.$http.post('/api/gjPstpsyjlb/getGztpBase');
			if(res.success){
				if(res.data){
					this.psdds=res.data;
				}
			}
			else{
				this.psdds=[];
			}
		},
		retType(type,str) {
			var rets = '';
			if(str==1){
				// 状态
				this.status.forEach((cell,idx)=>{
					if(type==cell.key){
						rets=cell.value;
						return;
					}
				});
			}
			else if(str==2){
				var depts=JSON.parse(uni.getStorageSync("bmbms"));
				// 部门
				depts.forEach((cell,idx)=>{
					if(type==cell.dwbm){
						rets=cell.dwmc;
						return;
					}
				});
			}
			return rets;
		}
		
	}
}; 
 
</script>

<style lang="scss" scoped>
page {
  height: 100%;
  background-color: #f5f5f5;
}

::v-deep .uni-collapse-item__wrap{
	background-color: #f9f9f9 !important;
}
::v-deep .uni-collapse-item__wrap-content.uni-collapse-item--border{
	border-bottom-width:0 !important;
}
::v-deep .uni-collapse-item__title-arrow{
	margin-right: 0 !important;
}
::v-deep .u-list-item{
	background-color: #ffffff !important;
}
::v-deep .uni-icons{
	font-size: 32rpx !important;
}

.new-data-box {
	width: 600rpx;
	height: 800rpx;
	margin: 70rpx 30rpx;
}

.container {
  min-height: 100%;
  padding-bottom: 120rpx;
  box-sizing: border-box;
}

.navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
  padding: 0 30rpx;
  background-color: #fff;
  position: relative;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.nav-left {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nav-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.nav-right .complete-btn {
  font-size: 30rpx;
  color: #007aff;
}

.section {
  margin: 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.input-group {
	display: flex;
	flex-direction: row;
	align-items: center;
	width: 100%;
}

.label {
  display: block;
  font-size: 30rpx;
  color: #333;
  margin-right: 10rpx;
}

.input-container {
  display: flex;
  flex:1;
  align-items: center;
  border: 2rpx solid #ddd;
  border-radius: 12rpx;
  padding: 10rpx 16rpx;
}

.input-field {
  flex: 1;
  font-size: 30rpx;
  color: #333;
}

.scan-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.hint {
  display: block;
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
}

.scan-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60rpx 30rpx;
  border: 4rpx dashed #ddd;
  border-radius: 16rpx;
  cursor: pointer;
}

.scan-icon {
  margin-bottom: 20rpx;
}

.scan-title {
  font-size: 32rpx;
  color: #333;
  margin-bottom: 10rpx;
}

.scan-desc {
  font-size: 26rpx;
  color: #999;
}

.order-details {
  margin-top: 30rpx;
}

.detail-header {
  padding-bottom: 20rpx;
  border-bottom: 2rpx solid #eee;
  margin-bottom: 20rpx;
}

.detail-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.detail-item {
  display: flex;
  margin-bottom: 15rpx;
}

.item-label {
  font-size: 28rpx;
  color: #666;
  width: 180rpx;
}

.item-value {
  font-size: 28rpx;
  color: #333;
  flex: 1;
}

.list-section {
  margin-top: 25rpx;
}

.list-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 15rpx;
}

.list-item {
  padding: 15rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.item-text {
  font-size: 28rpx;
  color: #555;
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 25rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.section-count {
  font-size: 28rpx;
  color: #999;
  margin-left: 10rpx;
}

.pallet-list {
  margin-bottom: 30rpx;
}

.pallet-card {
  background-color: #f9f9f9;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.pallet-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10rpx;
  margin-right: 10rpx;
}

.pallet-number {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  display: flex;
  flex: 1;
}

.pallet-status {
  font-size: 24rpx;
  color: #999;
  padding: 5rpx 15rpx;
  border-radius: 20rpx;
  background-color: #f0f0f0;
  margin-right: 10rpx;
}

.pallet-status.status-zp{
  color: #4cd964;
  background-color: #f0faf4;
}
.pallet-status.status-ps{
  color: #e6a23c;
  background-color: #faecd8;
}
.pallet-status.status-zz{
  color: #6366F1;
  background-color: #E0E7FF;
}
.pallet-status.status-js{
  color: #8B5CF6;
  background-color: #EDE9FE;
}
.pallet-status.status-xp{
  color: #f56c6c;
  background-color: #fde2e2;
}


.pallet-status.status-completed {
  color: #4cd964;
  background-color: #f0faf4;
}

.pallet-materials {
  margin-bottom: 10rpx;
}

.material-text {
  display: block;
  font-size: 26rpx;
  color: #666;
  margin-bottom: 5rpx;
}

.pallet-time {
  text-align: right;
}

.time-text {
  font-size: 24rpx;
  color: #999;
}

.add-pallet-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 80rpx;
  background-color: #007aff;
  border-radius: 12rpx;
  color: #fff;
  font-size: 30rpx;
  cursor: pointer;
}

.btn-text {
  margin-left: 10rpx;
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-top: 2rpx solid #eee;
  box-sizing: border-box;
}

.action-btn {
  flex: 1;
  height: 80rpx;
  border-radius: 12rpx;
  font-size: 32rpx;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
}

.continue-btn {
  background-color: #007aff;
  color: #fff;
  margin-right: 20rpx;
}

.complete-btn {
  background-color: #4cd964;
  color: #fff;
}
</style>

