<template>
  <view class="report_content">
    <view class="header">
      <view class="header_content">
        <view class="title">本次{{ type == "exam" ? "测评" : "学习" }}概览</view>
        <view class="content">
          <view class="content_row">
            <view class="main">{{ type == "exam" ? formatTime(reportInfo.exam_time) : formatTime(reportInfo.video_lasttime - reportInfo.video_inittime) }}</view>
            <view class="tip">学习时长</view>
          </view>
          <view class="content_row">
            <view class="main">{{ reportInfo.isanswer_total + "/" + reportInfo.answer_total }}</view>
            <view class="tip">答对题目</view>
          </view>
          <view class="content_row">
            <view class="main">{{ reportInfo.get_score }}</view>
            <view class="tip">获得积分</view>
          </view>
        </view>
      </view>
    </view>
    <view class="content">
      <view class="title">答题情况</view>
      <view class="content_list">
        <view class="conent_main" v-for="(item, index) in queston_list" :key="index">
          <view class="item_num">
            <view class="item_answer"><icon :type="item.is_answer == 0 ? 'cancel' : 'success'" size="20" /> &nbsp;第{{ index + 1 }}题</view>
            <view :style="item.get_score > 0 ? 'color:green' : 'color:red'">+{{ item.get_score }}&nbsp;积分</view>
          </view>
          <view class="item_title">{{ item.question_title }}</view>
        </view>
      </view>
    </view>
    <view class="bottom_btn">
      <view class="submit_btn defult" v-if="reportInfo?.is_self"  @click="showShareImage">生成分享图</view>
	  <view class="submit_btn start_learn" v-if="!reportInfo?.is_self" @click="toLearn">开启我的学习计划</view>
      <view class="submit_btn" v-if="reportInfo?.is_self" @click="_continue">{{ type == "exam" ? "重新练习" : "继续课后评测" }}</view>
    </view>
	<uni-popup ref="filePathPopup" type="center" class="center_popup" >
		<view class="cover_black" :style="windowWidth">
			<image v-if="filePath" :src="filePath" mode="heightFix" class="file_path_image"></image>
			<view class="bottom_box">
				<view class="info_title">
					<view class="title_center">分享至</view>
					<button class="close_popup" @click.stop="closePupop"> X </button>
				</view>
				<button class="save_image_btn" @click.stop="saveImage">
					<image class="save_icon" src="https://kailin-mp.oss-cn-shenzhen.aliyuncs.com/static/video/savepic.png" mode=""></image>
					<view class="save_text">保存图片</view>
				</button>
			</view>
		</view>
	</uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      reportInfo: {
        exam_time: 0,
        isanswer_total: 0,
        answer_total: 0,
        get_score: 0,
		is_self:1,
      },
	  filePath:"",
      queston_list: [],
      record_id: null,
      type: null, // 确保 type 在 data 中定义
	  windowWidth:{},
    };
  },
  onLoad(params) {
    console.log("params:", params); // 获取到query参数
    this.record_id = params.record_id;
    this.type = params.type;
    //分享按钮
    uni.showShareMenu({
      withShareTicket: true,
      menus: ["shareAppMessage", "shareTimeline"],
    });
  },
  onShow() {
    this._getRecord(this.type);
    this._getAnswerList(this.type);
	this.windowWidth = {height:uni.getWindowInfo().windowHeight+'px'};
  },
  onShareAppMessage(obj) {
    return {
      title: `999智控终端平台\n学习报告`,
      path: `/pages/video/record?type=${this.type}&record_id=${this.record_id}`,
	  promise: new Promise((resolve, reject) => {
	    this.$http.request(`api/${this.type}_report_share_image/get`, {course_id: this.reportInfo.course_id,record_id:this.record_id}).then((callback) => {
	      let obj = {
	        title: callback.data?.title,
	        path: `/pages/video/record?type=${this.type}&record_id=${this.record_id}`,
	      };
		  if (callback.data?.image_url !== "") {
		    obj.imageUrl = callback.data.image_url;
		  }
		  resolve(obj);
	    });
	  }),
    };
  },
  methods: {
	toLearn(){
		if( !this.reportInfo?.course_id ) {
			uni.showToast({
				icon:"none",
				title:"无对应课程ID",
			})
			return ;
		}
		uni.redirectTo({
		  url: `/pages/video/detail?id=${this.reportInfo.course_id}`,
		});
	},
	showShareImage(){
		this.$http.request(`api/${this.type}_report_share_image/get_after`, {course_id: this.reportInfo.course_id,record_id:this.record_id,scene:`type=${this.type}&record_id=${this.record_id}`}).then((callback) => {
		  if( callback.code == 'success'){
				// 分离base64中的数据部分
			  const imgSrc = callback.data?.base64_image; // 假设这是你的base64字符串，例如："data:image/png;base64,iVBORw0K..."
			  const imgFormat = imgSrc.split(',')[1]; // 获取base64编码的图片数据部分
			  const fileExt = imgSrc.split(';')[0].split('/')[1]; // 获取图片格式，例如：jpeg, png等
			  const filePath = `${uni.env.USER_DATA_PATH}/${Date.now()}.${fileExt}`; // 临时文件路径，使用用户数据路径确保有权限写入
			  // 使用uni.getFileSystemManager()将base64转换为文件并保存到相册
			  const fs = uni.getFileSystemManager();
			  fs.writeFile({
				filePath: filePath,
				data: imgFormat, // 直接写入base64编码的数据部分，不需要转换ArrayBuffer
				encoding: 'base64', // 指定编码为base64
				success: () => {
				  this.filePath = filePath
				  // 显示
				  this.$refs.filePathPopup.open("center");
				},
				fail: function (err) {
				  console.log('文件写入失败', err);
				  uni.showToast({ title: '文件写入失败', icon: 'none' });
				}
			  });
		  }
		});
	},
	saveImage(){
		if( this.filePath ){
			uni.saveImageToPhotosAlbum({
			  filePath: this.filePath,
			  success:()=>{
				// 关闭结果
				this.$refs.filePathPopup.close();
			    uni.showToast({ title: '保存成功', icon: 'success' });
			  },
			  fail:(err)=> {
			    uni.showToast({ title: '保存失败', icon: 'none' });
			  }
			});
		}
	},
	closePupop(){
		this.$refs.filePathPopup.close();
	},
    _backList() {
      uni.redirectTo({
        url: `/pages/video/index`,
      });
    },
    _continue() {
      uni.redirectTo({
        url: `/pages/video/exam?id=${this.reportInfo.course_id}`,
      });
    },
    _getRecord(type) {
      this.$http
        .request(`api/video_${type}_record/get_report`, {
          record_id: this.record_id,
        })
        .then((re) => {
          if (re.code == "success") {
            console.log(re.data);
            this.reportInfo = re.data;
          }
        });
    },
    _getAnswerList(type) {
      this.$http
        .request(`api/video_${type}_answer/get_list`, {
          record_id: this.record_id,
        })
        .then((re) => {
          if (re.code == "success") {
            console.log(re.data);
            this.queston_list = re.data;
          }
        });
    },
    formatTime(seconds) {
      const minutes = Math.floor(seconds / 60);
      const remainingSeconds = seconds % 60;
      return `${String(minutes).padStart(2, "0")}:${String(remainingSeconds).padStart(2, "0")}`;
    },
  },
};
</script>

<style lang="less" scoped>
.report_content {
  .header {
    width: 100vw;
    padding: 36rpx;
    box-sizing: border-box;
    .header_content {
      height: 360rpx;
      width: 100%;
      background: linear-gradient(to bottom right, #6765f1, #a556f7);
      border-radius: 20rpx;
      color: #fff;
      padding: 36rpx;
      box-sizing: border-box;
      .content {
        height: calc(100% - 55rpx);
        display: flex;
        align-items: center;
        justify-content: space-between;
        .content_row {
          display: flex;
          flex-direction: column;
          align-items: center;
          .main {
            font-size: 52rpx;
            font-weight: bold;
            margin-bottom: 20rpx;
          }
          .tip {
            color: #bba6ff;
            font-size: 28rpx;
          }
        }
      }
    }
  }
  > .content {
    width: 100vw;
    padding: 36rpx;
    box-sizing: border-box;
    > .title {
      font-size: 32rpx;
      font-weight: bold;
      margin-bottom: 36rpx;
    }
    > .content_list {
      width: 100%;
      height: calc(100vh - 750rpx);
      overflow: auto;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      gap: 20rpx;
      .conent_main {
        border: 1px solid #ddd;
        box-shadow: 0 2px 4px 0 rgba(204, 204, 204, 0.5); /* 添加背景阴影 */
        width: 100%;
        padding: 20rpx;
        box-sizing: border-box;
        border-radius: 6rpx;
        display: flex;
        flex-direction: column;
        gap: 20rpx;
        .item_num {
          display: flex;
          justify-content: space-between;
          align-items: center;
        }
        .item_answer {
          display: flex;
          align-items: center;
        }
      }
    }
  }
  .bottom_btn {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 150rpx;
    border-top: 4rpx solid #ddd;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 40rpx;
    box-sizing: border-box;
    .answer_info {
      display: flex;
      align-items: baseline;
    }
    .submit_btn {
      background-color: #5045e6;
      color: #fff;
      font-size: 28rpx;
      width: 45%;
      height: 80rpx;
      line-height: 80rpx;
      border-radius: 8rpx;
      box-shadow: 2rpx 2rpx 8rpx rgba(0, 0, 0, 0.1);
      text-align: center;
      &.defult {
        background-color: #fff;
        color: #333;
      }
    }
	.submit_btn.start_learn{
		width: 90%;
		margin: 0rpx auto;
	}
  }
}
.center_popup{
	.cover_black{
		display: block;
		width: 750rpx;
		position: relative;
		padding-top: 120rpx;
		background-color: rgba(0, 0, 0, 0.9);
		.file_path_image{
			top: 50%;
			left: 50%;
			width: 622rpx;
			height: 892rpx;
			display: block;
			position: absolute;
			margin-top: -560rpx;
			margin-left: -311rpx;
		}
		.bottom_box{
			left: 0rpx;
			bottom: 0rpx;
			width: 750rpx;
			height: 300rpx;
			position: absolute;
			background-color: #FFFFFF;
			border-top-left-radius: 20rpx;
			border-top-right-radius: 20rpx;
			.info_title{
				display: block;
				border: none;
				width: 750rpx;
				height: 60rpx;
				line-height: 60rpx;
				font-size: 28rpx;
				text-align: center;
				position: relative;
				.title_center{
					display: block;
					border: none;
					width: 120rpx;
					height: 60rpx;
					line-height: 60rpx;
					font-size: 28rpx;
					margin: 0rpx auto;
					text-align: center;
				}
				.close_popup{
					top: 0rpx;
					right: 0rpx;
					border: none;
					width: 60rpx;
					height: 60rpx;
					font-size: 32rpx;
					padding: 0rpx 0rpx;
					line-height: 60rpx;
					position: absolute;
					background-color: transparent;
				}
				.close_popup::after{
					border: none;
					background-color: transparent;
				}
			}
			.save_image_btn{
				display: block;
				border: none;
				width: 300rpx;
				height: 120rpx;
				margin: 0rpx auto;
				overflow: hidden;
				margin-top: 40rpx;
				padding: 0rpx 0rpx;
				text-align: center;
				line-height: 80rpx;
				vertical-align: middle;
				background-color: transparent;
				.save_icon{
					float: left;
					width: 80rpx;
					height: 80rpx;
				}
				.save_text{
					float: left;
					width: 180rpx;
					height: 80rpx;
					font-size: 32rpx;
				}
			}
			.save_image_btn::after{
				border: none;
				background-color: transparent;
			}
		}
	}
}
</style>
