<template>
  <view class="page flex-col">
    <view class="group_1 flex-row">
      
      
    </view>
    <view class="group_2 flex-row">
      <image
        class="label_1"
        referrerpolicy="no-referrer"
        src="/static/lanhu_kaoshijieguo/FigmaDDSSlicePNGacf527a62cbe7351c6472edd8f5b2814.png"
		@click="handleBack()"
      />
      <text class="text_1">考试结果</text>
      
    </view>
    <view class="group_4 flex-col">
      <view class="block_1 flex-row justify-between" @click="show = true">
        <text class="text_19">是否通过</text>
        <view class="image-text_1 flex-row justify-between">
          <!-- <text class="text-group_2">已通过</text> -->
		  
		  	<view>
		  		<u-picker v-model="process.examStatus"  :show="show" :columns="ifPassColumns" title="是否通过" @confirm="ifPassOnConfirm" @cancel="show = false">
				</u-picker>
				<text class="text-group_2">{{ selectedValue || '请选择' }}</text>
		  		<!-- <u-button @click="show = true"><text class="text-group_2">{{ selectedValue || '请选择' }}</text></u-button> -->
		  	</view>
		  
          <!-- <image
            class="thumbnail_2"
            referrerpolicy="no-referrer"
            src="/static/lanhu_kaoshijieguo/FigmaDDSSlicePNGe9aade9ef56a9cabc28f2f1b0555105b.png"
          /> -->
        </view>
      </view>
      <view class="text-wrapper_7 flex-row justify-between">
        <text class="text_4">分数</text>
		<view class="text_5_1 ">
		<u--input
		    placeholder="请输入分数"
		    border="none"
		    v-model="process.examScore"
			maxlength="3"
			inputAlign="right"
		  >分</u--input>
        </view>
      </view>
      <view class="text-wrapper_8 flex-row justify-between">
        <text class="text_20">时间</text>
		<view>
			<u-datetime-picker
			  :show="showTimePicker"
			  v-model="process.examTime"
			  mode="datetime"
			  @confirm="onConfirmExamTime"
			  @cancel="showTimePicker = false"
			></u-datetime-picker>
			<text class="text_3" @click="showTimePicker = true">{{ process.examTime ? formatDate(process.examTime) : '选择时间' }}</text>
			
				<!-- <u-button @click="showTimePicker = true">打开</u-button> -->
			</view>
        
		
      </view>
      <view class="text-wrapper_9 flex-row justify-between">
        <text class="text_6">姓名</text>
        <view class="text_5_1 ">
        <u--input
            placeholder="请输入姓名"
            border="none"
            v-model="process.userName"
        	maxlength="3"
        	inputAlign="right"
          >分</u--input>
        </view>
      </view>
      <view class="text-wrapper_10 flex-row justify-between">
        <text class="text_8">考试类型</text>
        <text class="text_9">C1</text>
      </view>
      <view class="text-wrapper_11 flex-row justify-between" @click="subjectShow = true">
        <text class="text_10">考试科目</text>
		<view>
			<u-picker v-model="process.subject"  :show="subjectShow" :columns="subjectColumns" title="科目" @confirm="subjectOnConfirm" @cancel="subjectShow = false">
			</u-picker>
			<text class="text-group_2">{{ subjectValue || '请选择科目' }}</text>
			<!-- <u-button @click="show = true"><text class="text-group_2">{{ selectedValue || '请选择' }}</text></u-button> -->
		</view>
        <!-- <text class="text_11">科目二</text> -->
      </view>
      <!-- <view class="text-wrapper_12 flex-row justify-between">
        <text class="text_12">考试地址</text>
        <text class="text_13">山东省济南市历下区</text>
      </view>
      <view class="text-wrapper_13 flex-row justify-between">
        <text class="text_14">交通方式</text>
        <text class="text_15">公交车</text>
      </view> -->
    </view>
    <view class="group_5 flex-col">
      <text class="text_16">备注</text>
      <u--textarea class="text_17" v-model="process.remark" placeholder="请输入内容" count ></u--textarea>
      <text class="text_18">图片</text>
      <view class="image-wrapper_4 flex-row justify-between">
		  <u-upload
		    
			:fileList="displayFileList"
		    @afterRead="afterRead"
		    @delete="deletePic"
		    multiple
		    :maxCount="2"
		  ></u-upload>
        <!-- <image
          class="image_3"
          referrerpolicy="no-referrer"
          src="/static/lanhu_kaoshijieguo/FigmaDDSSlicePNG531b2664a25a7d42a43f00faa060acb1.png"
        />
        <image
          class="image_4"
          referrerpolicy="no-referrer"
          src="/static/lanhu_kaoshijieguo/FigmaDDSSlicePNG66b1c863f069a58fb4ff203ed443e5ad.png"
        /> -->
      </view>
    </view>
	<view class="block_8 flex-col">
	  <view class="text-wrapper_8 flex-col" @click="saveData()">
	    <text class="text_19">确定</text>
	  </view>
	</view>
  </view>
</template>
<script>
	import upload from '@/utils/upload.js'
	import request from '@/utils/request.js'
import { getLocalUserInfo } from '../../utils/auth';
export default {
  data() {
    return {
		show: false,
		showTimePicker: false,
		subjectShow: false,
		ifPassColumns: [['已通过', '未通过']],
		subjectColumns: [['科目一', '科目四' ]],
		selectedValue: '', 
		subjectValue: '',
		fileList: [],
		imageUrl: this.$imagesUrl,
		userInfo: [],
		process: {
			userName: null,
			userId: null,
			subject:null,
			courseType: null,
			examNum: null,
			examStatus: null,
			examScore: null,
			remark: '',
			examTime: null,
			images: null,
			tenantId: null,
			
		},
      constants: {}
    };
  },
  onLoad() {
  	this.userInfo = getLocalUserInfo()
	this.getUserOrderDetails()
  },
  computed: {
    displayFileList() {
      return this.fileList.map(item => {
        // 如果 url 已经是完整路径（http/https），直接使用
        if (item.url.startsWith('http')) {
          return item;
        }
        
        // 否则拼接全局前缀（注意处理路径分隔符）
        const prefix = this.$imagesUrl.endsWith('/') ? this.$imagesUrl : `${this.$imagesUrl}/`;
        const fullUrl = item.url.startsWith('/') 
          ? `${prefix}${item.url.slice(1)}`  // 避免双斜杠（如 https://domain.com//path）
          : `${prefix}${item.url}`;          // 直接拼接（如 https://domain.com/path）
        
        return {
          ...item,
          url: fullUrl,
        };
      });
    },
  },
  methods: {
	  handleBack() {
	    uni.navigateBack({
	    	delta: 1 
	    });
	  },
	  ifPassOnConfirm(value) {
	      console.log('选中的值:', value);
	      
	      const statusMap = {
	        '已通过': 1,
	        '未通过': 0
	      };
	  
	      // 更新数据
	      this.process.examStatus = statusMap[value.value[0]]; // 存储数值\
		  console.log('value[0]', value.value[0])
	      this.selectedValue = value.value[0]; // 存储文字，供页面显示
	      this.show = false; // 关闭弹窗
	  
	      console.log('examStatus:', this.process.examStatus);
		 console.log('process', this.process)
	    },
		
		subjectOnConfirm(value) {
		    console.log('选中的值:', value);
		    
		    const statusMap = {
		      '科目一': 1,
		      '科目四': 4
		    };
		
		    // 更新数据
		    this.process.subject = statusMap[value.value[0]]; // 存储数值\
				  console.log('value[0]', value.value[0])
		    this.subjectValue = value.value[0]; // 存储文字，供页面显示
		    this.subjectShow = false; // 关闭弹窗
		
		    console.log('subject:', this.process.subject);
				 console.log('process', this.process)
		  },
		  
		onConfirmExamTime(value) {
		    console.log("选中的时间:", value);
		    this.process.examTime = value; // 保存到 process.examTime
		    this.showTimePicker = false; // 关闭时间选择器
		  },
		  // 格式化时间戳的方法
		      formatDate(timestamp) {
		        const date = new Date(timestamp);
		        const year = date.getFullYear();
		        const month = String(date.getMonth() + 1).padStart(2, '0');
		        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}`;
		      },
			  
		// 删除图片
		      /* deletePic(event) {
		      	this[`fileList${event.name}`].splice(event.index, 1)
		      	if (event.name == '1') {
		      		this.photoUrl.splice(event.index, 1)
		      	}
		      	if (event.name == '2') {
		      		this.videoUr = null
		      	}
		      
		      }, */
			  deletePic(event) {
			    this.fileList.splice(event.index, 1); // 直接操作唯一的 fileList
			  },
		      // 新增图片
		      async afterRead(event) {
		        let lists = [].concat(event.file); // 兼容单个和多个文件
		        let fileListLen = this.fileList.length;
		      
		        for (let i = 0; i < lists.length; i++) {
		          try {
		            const resultUrl = await this.uploadFilePromise(lists[i].url); // 上传图片并获取 URL
		            let item = {
		              status: 'success',
		              url: resultUrl, // 服务器返回的 URL
		            };
		            this.fileList.splice(fileListLen, 0, item);
		            fileListLen++;
		          } catch (error) {
		            console.error('图片上传失败', error);
		          }
		        }
		      },
		      uploadFilePromise(filePath) {
				  console.log('图片地址', filePath)
		        return new Promise((resolve, reject) => {
		          upload({
		            url: '/app-api/small-upload/common/upload',
		            filePath: filePath,
		          }).then((res) => {
		            if (res.data && res.data.url) {
		              resolve(res.data.url); // 返回图片 URL
					  console.log('返回', res)
					  console.log('返回url', res.data.url)
		            } else {
		              reject(new Error('上传失败'));
		            }
		          }).catch(err => reject(err));
		        });
		      },
			  
			  getUserOrderDetails() {
			        request({
			          url: '/app-api/small/drive/school-course-order/page',
			          method: 'GET',
			          params: {
			            userId: this.userId,
			  			paymentStatus:'2',
						ifEnd: 0,
			          },
			  		tenantIdFlag : false
			        }).then(res => {
			          this.orderList = res.data.records;
			  			  console.log('订单信息',res.data)
					  
			        });
			      },
			  
			  saveData() {
				  this.process.userId = this.userInfo.id
				  this.process.tenantId = this.userInfo.tenantId
			    // 1. 拼接图片 URL
			    this.process.images = this.fileList?.map(item => item.url).join(',') || '';
				console.log('process', this.process)
			  
			    // 2. 校验必填字段（可选）
			    if (!this.process.userId || !this.process.subject) {
			      uni.showToast({ title: '用户ID和科目不能为空', icon: 'none' });
			      return;
			    }
			  
				request({
					url: '/app-api/process/updateProcess',
					method: 'PUT',
					data: this.process,
				}).then(res => {
					if(res.code === 0){
						 uni.showToast({ 
						      title: '保存成功', 
						      icon: 'success',
						      duration: 1000 
						    });
						setTimeout(() => {
						      uni.navigateTo({
						        url: '/newPages/examinationList/index' 
						      });
						    }, 1500); 
					}else{
						uni.showToast({ title: res.data?.message || '保存失败', icon: 'none' });
					}
				})
			  }
		
  }
};
</script>
<style lang='scss'>
@import '../common/common.scss';
@import './assets/style/index.rpx.scss';

</style>
