<template>
	<view class="content">
		<view class="navbar_section">
		  <view class="title">首页</view>
		</view>
		<view class="head">
			<view class="head-img">
				<!-- <fui-avatar width="136" :src="$util.img(member_info.headimg)"></fui-avatar> -->
        <image class="pic" :src="member_info.memberHasOne ? member_info.memberHasOne.headimg : $util.img('/uniapp_src/static/images/common/yong_hu.png')"></image>
				<view class="head-text">{{member_info.name}}</view>
			</view>
		</view>
		<view class="card">
			<view class="card-back color-style"></view>
			<view class="card-backs color-style"></view>
			<view class="card-con">
<!--				<view class="card-head">-->
<!--					<view>-->
<!--						<span class="card-head-txt">班级</span>-->
<!--						<span class="card-head-txt1 card-head-back1">篮球少儿班</span>-->
<!--					</view>-->
<!--					<view>-->
<!--						<span class="card-head-txt">已耗课时</span>-->
<!--						<span class="card-head-txt1 card-head-back2">24/</span><span class="card-head-txt">60</span>-->
<!--					</view>-->
<!--				</view>-->
<!--				<view class="card-con-txt">课程到期时间：2021.12.25</view>-->

				<view class="card-con-txt1">
					<view class="card-con-txt1-left">
						<image :src="$util.img('/uniapp_src/static/images/index/score.png')" class="overlay-image"></image>
						<view class="card-con-txt1-left-txt top">{{physicalTestInfo.calculateChildHealthScore}}</view>
						<view class="card-con-txt1-left-txt top1">综合评分</view>
					</view>
					<view class="card-con-txt1-right">
						<view style="color: #AAAAAA;padding: 5rpx;">数据测评时间：{{$util.formatToDateTime(physicalTestInfo.created_at,'Y-m-d')}}</view>
						<view style="display: flex;justify-content: space-around;margin-top: 20rpx;">
							<view>
								<view style="font-size: 48rpx;color: #29d3b4;">{{physicalTestInfo.height}}</view>
								<view style="color: #AAAAAA;font-size: 30rpx;">身高（CM）</view>
							</view>
							<view>
								<view style="font-size: 48rpx;color: #29d3b4;">{{physicalTestInfo.weight}}</view>
								<view style="color: #AAAAAA;font-size: 30rpx;">体重（KG）</view>
							</view>
						</view>
					</view>
				</view>
				<view class="more" @click="physical_examination()">更多</view>
			</view>

			<view class="upcomin-classes">
				<view class="upcomin-classes-div">
					<view class="upcomin-classes-div-con">
						<view class="upcomin-classes-div-con-left">课程预告</view>
						<view class="upcomin-classes-div-con-centre"
							style="width: 2rpx;height: 60rpx;background-color: #fff;margin-left: 25rpx;"></view>
						<view style="margin-left: 25rpx;">
							<view>{{$util.formatToDateTime(memberIndexData.kcyg.date_time,'m-d')}} {{memberIndexData.kcyg.weekday}} {{memberIndexData.kcyg.time_slot[0]}}-{{memberIndexData.kcyg.time_slot[1]}}</view>
							<view>{{memberIndexData.kcyg.address}} {{memberIndexData.kcyg.courses_name}}</view>
						</view>
						<view class="upcomin-classes-div-con-right" @click="openViewTimetableInfo(memberIndexData.kcyg)">
							详情
						</view>
					</view>
				</view>
			</view>

			<view class="after-class">
				<view class="after-class-title">
					<view class="after-class-title-left">课后作业</view>
					<view class="after-class-title-right" @click="jobList">全部</view>
				</view>

				<view class="after-class-con" v-for="(v,k) in jobAssignmentsInfo" :key="k" @click="openViewWorkDetails(v)">
					<view class="after-class-con-txt">
						<view style="width: 25%;margin-top: 5%;">
							<view style="font-size: 55rpx;color: #fff;"><span style="color: #29d3b4;">12</span>/23
							</view>
							<view style="font-size: 35rpx;color: #ccc;padding-left: 10rpx;">已完成</view>
						</view>
						<view style="width: 70%;">
							<view style="color: #fff;display: flex;justify-content: space-between;align-items: center;">
								<view style="display: flex;align-items: center;">
									<image :src="$util.img(v.coach_pic)" style="width: 50rpx;height: 50rpx;">
									</image>
									<span style="padding-left: 10rpx;font-size: 35rpx;">{{v.coach_name}}</span>
								</view>
								<view>
									<fui-button background="#404045" color="#F59A23" borderColor="#F59A23"
										btnSize="mini" @click="submitJob(v)">上传</fui-button>
								</view>
							</view>
							<view style="color: #fff;padding: 10rpx;">时间：{{v.create_time}}</view>
							<view class="multi-line-ellipsis" v-html="v.content_text">

              </view>
						</view>
					</view>
				</view>

				<view class="item" v-for="(v,k) in assignmentsList" :key="k" @click="openViewWorkDetails(v)">
          <view class="multi-line-ellipsis text-style" v-html="v.content_text"></view>
          <view style="width: 92%;margin: auto;border-radius: 15rpx;" v-if="v.student_file">
            <video v-if="v.student_file_type == 2" style="width: 100%;border-radius: 15rpx;"  :src="$util.img(v.student_file)"></video>
            <image v-else style="width: 100%;border-radius: 15rpx;" :src="$util.img(v.student_file)" mode="aspectFit"></image>
          </view>
        </view>

<!--				<view class="multi-line-ellipsis text-style">-->
<!--					作业描述作业描述作业描述作业描述作业描述作业描述作业描述作业描述作业描述作业描述作业描述作业描述作业描述作业描述作业描述作业描述作业描述作业描述</view>-->
<!--				<view style="width: 92%;margin: auto;border-radius: 15rpx;">-->
<!--					<video style="width: 100%;border-radius: 15rpx;"></video>-->
<!--				</view>-->


			</view>
			<view style="height: 180rpx;width: 100%;"></view>
		</view>
		<AQTabber />
	</view>
</template>

<script>
  import {Api_url} from "@/common/config";
	import apiRoute from '@/api/apiRoute.js';

	import memberApi from '@/api/member.js';
	import AQTabber from "@/components/AQ/AQTabber.vue"
	export default {
		components: {
			AQTabber,
		},
		data() {
			return {
        inited: false, // 添加标记位控制 init 只执行一次

        //上传接口地址
        uploadApiUrl: ``,
        uploadImageApiUrl: `${Api_url}/file/image`,
        uploadVideoApiUrl: `${Api_url}/file/video`,

				member_info: {},//学生信息

        assignmentsList: [],//作业列表
        jobAssignmentsInfo: [],//待完成的作业

        memberIndexData:{
          tx:{//体测信息
            height: '', // 身高（单位：米）
            weight: '', // 体重（单位：公斤）
            score: '', // 综合评分
            create_time: '' // 体测时间
          },
          kcyg: { // 课程预告信息
            id: '', // 课程ID
            date_time: "", // 课程日期
            time_slot: "", // 课程时间段
            address: "", // 课程地点
            courses_name: "", // 课程名称
            date_md: "", // 课程日期（月/日格式）
            weekday: "" // 课程星期
          }
        },//首页数据

        path_arr:{
          '1':'/pages/coach/home/index',//教练
          '2':'/pages/market/index/index',//销售
          '3':'/pages/student/index/index',//学员
        },
        thisPath:'',//当前页面的路径(默认'')
        openPath:'',//正确的跳转路径(默认'')

        physicalTestInfo:{
          created_at:'',//测评时间
          calculateChildHealthScore:'0',//综合评分
          height:'0',//身高
          weight:'0',//体重
        },//体测报告详情
			}
		},
		onLoad() {
      this.openViewHome()//检测首页是否正确跳转-不正确则进行重定向
		},
    onShow(){
      // 防止 onShow 触发后重复 init
      if (!this.inited) {
        this.init()
        this.inited = true
      }
    },
		methods: {
		  //学生页面初始化
      async init(){
        await this.member_init()
        await this.getPhysicalTestList()
        this.getMemberIndex()
        this.getList()
        this.getJobAssignmentsInfo()
      },

      //获取体测列表
      async getPhysicalTestList(){
        let params = {
          page: 1,//当前页码
          limit: 1,//每页返回数据条数
          total: 1,//数据总条数
          resource_id:this.member_info.id,//学生资源表id
        }
        let res  = await apiRoute.xy_physicalTest(params)
        if(res.code != 1){
          uni.showToast({
            title: res.msg,
            icon: 'none'
          })
        }

        console.log('tc',res.data)

        let arr = res.data.data
        if(arr.length){
          this.physicalTestInfo = arr[0]
        }
      },



      async openViewHome_COPY(){
        //获取当前页面路径
        let pages = getCurrentPages();
        //当前页面路径
        this.thisPath = '/' + pages[0].route
        //获取缓存用户登陆类型
        let userType = String(uni.getStorageSync('userType'))

        this.openPath = this.path_arr[userType]

        console.log(
            '跳转',
            this.thisPath,
            userType,
            this.path_arr[userType]
        )
        if(this.thisPath != this.openPath){
          console.log('打印1')
          //跳转tabBar首页-页面
          uni.setStorageSync('tabBerIndex', 0)
          uni.navigateTo({
            url: this.openPath
          })
          return
        }else{
          //页面正确的情况下->执行学生页面初始化
          this.init()
        }
      },

      async getMemberIndex(){
        let res = await memberApi.memberIndex({})
        if(res.code != 1){
          uni.showToast({
            title: res.msg,
            icon: 'none'
          })
          return
        }
        // console.log('首页',res)

        if(res.data.kcyg.time_slot){
          res.data.kcyg.time_slot = res.data.kcyg.time_slot.split(',');
        }

        this.memberIndexData = res.data
      },

      //获取作业列表
      async getList(){
        let data = {
          page: 1,
          limit: 10,
          status: '2',//1=未提交,2=已提交,3=已批改
        }
        let res = await memberApi.assignmentsList(data)
        if(res.code != 1){
          uni.showToast({
            title: res.msg,
            icon: 'none'
          })
          return
        }
        this.assignmentsList = res.data.data
        // console.log('作业列表',this.assignmentsList)
      },

      //获取待提交的作业列表
      async getJobAssignmentsInfo(){
        let data = {
          page: 1,
          limit: 1,
          status: '1',//1=未提交,2=已提交,3=已批改
        }
        let res = await memberApi.assignmentsList(data)
        if(res.code != 1){
          uni.showToast({
            title: res.msg,
            icon: 'none'
          })
          return
        }
        this.jobAssignmentsInfo = res.data.data

        // console.log('待提交的作业',this.jobAssignmentsInfo)
      },

			//获取学员信息
			async member_init() {
        let res = await apiRoute.xy_memberInfo({})
        if(res.code != 1){
          uni.showToast({
            title: res.msg,
            icon: 'none'
          })
          return
        }
        this.member_info = res.data
        console.log('xxxx',this.member_info)
			},

      //跳转页面-作业详情
			details() {
				uni.navigateTo({
					url: '/pages/student/index/work_details'
				})
			},
      //跳转体测列表
			physical_examination(){
        let resource_id = this.member_info.id
				uni.navigateTo({
					url: `/pages/student/index/physical_examination?resource_id=${resource_id}`
				})
			},
      //跳转作业列表页
			jobList(){
				uni.navigateTo({
					url: '/pages/student/index/job_list'
				})
			},

      // 上传作业
      async submitJob(item) {
        let type = item.content_type // 作业类型1图片2视频

        try {
          // 等待上传文件的返回结果
          let uploadRes = await this.uploadFile(type)
          // console.log('上传结果', uploadRes)

          // 检查上传结果
          if (!uploadRes.data.path) {
            return
          }

          // 构建提交作业的数据
          let data = {
            id: item.id, // 作业列表id
            student_file: uploadRes.data.path, // 附件
            student_file_type: type, // 作业类型1图片2视频
            student_content: '', // 内容
          }

          // 提交作业
          await this.assignmentsSubmit(data)
        } catch (error) {
          console.error('上传或提交作业失败:', error)
          alert('上传或提交作业失败')
        }
      },

// 上传单文件(视频/图片) type=作业类型1图片2视频
      async uploadFile(type) {
        return new Promise((resolve, reject) => {
          if (type == 1) {
            this.uploadApiUrl = this.uploadImageApiUrl
            uni.chooseImage({
              count: 1,
              sizeType: ['compressed'],
              sourceType: ['album', 'camera'],
              success: async (res) => {
                const tempFilePath = res.tempFilePaths[0]
                // 这里可以调用上传接口
                try {
                  let data = await this.uploadFilePromise(tempFilePath)
                  resolve(data)
                } catch (error) {
                  reject(error)
                }
              },
              fail: (error) => {
                reject(error)
              }
            })
          } else {
            this.uploadApiUrl = this.uploadVideoApiUrl
            uni.chooseVideo({
              count: 1,
              // sizeType: ['compressed'],
              sourceType: ['album', 'camera'],
              success: async (res) => {
                // console.log('文件选择结果:', res); // 打印 res 检查是否有 tempFilePaths
                const tempFilePath = res.tempFilePath; // 直接获取视频文件路径
                // console.log('上传的文件',tempFilePath)

                // 这里可以调用上传接口
                try {
                  let data = await this.uploadFilePromise(tempFilePath)
                  resolve(data)
                } catch (error) {
                  reject(error)
                }
              },
              fail: (error) => {
                reject(error)
              }
            })
          }
        })
      },

      // 执行文件上传
      uploadFilePromise(url) {
        return new Promise((resolve, reject) => {
          let token = uni.getStorageSync('token') || ''
          uni.uploadFile({
            url: this.uploadApiUrl, // 仅为示例，非真实的接口地址
            filePath: url,
            name: 'file',
            header: {
              'token': `${token}`, // 请求头设置token
            },
            success: (e) => {
              let res = JSON.parse(e.data.replace(/\ufeff/g, "") || "{}")
              // console.log('上传成功2', res)
              if (res.code == 1) {
                resolve({
                  code: 1,
                  data: res.data,
                  msg: '上传成功'
                })
              } else {
                uni.showToast({
                  title: res.msg,
                  icon: 'none'
                })
                reject({
                  code: 0,
                  data: {},
                  msg: '上传失败'
                })
              }
            },
            fail: (error) => {
              reject(error)
            }
          })
        })
      },

      // 提交作业接口
      async assignmentsSubmit(item) {
        let data = {
          id: item.id, // 作业列表id
          student_file: item.student_file, // 附件
          student_file_type: item.student_file_type, // 作业类型1图片2视频
          student_content: item.student_content, // 内容
        }
        let res = await memberApi.assignmentsSubmit(data)
        if (res.code != 1) {
          uni.showToast({
            title: res.msg,
            icon: 'none'
          })
          return
        }
        uni.showToast({
          title: res.msg,
          icon: 'success'
        })
        // 延迟1s执行
        setTimeout(() => {
          this.init()
        }, 1000)
      },

      //跳转页面-打开作业详情
      openViewWorkDetails(item) {
        let id = item.id
        uni.navigateTo({
          url: `/pages/student/index/work_details?id=${id}`
        })
      },

      //跳转页面-打开课时详情
      openViewTimetableInfo(item) {
        let id = item.id
        uni.navigateTo({
          url: `/pages/student/timetable/info?id=${id}`
        })
      },


   }
	}
</script>

<style lang="less" scoped>
	
	//自定义导航栏
	.navbar_section{
	  display: flex;
	  justify-content: center;
	  align-items: center;
	  background: #29d3b4;
	  .title{
      padding: 40rpx 0rpx;

      /* 小程序端样式 */
      // #ifdef MP-WEIXIN
      padding: 80rpx 0rpx;
      // #endif


      font-size: 30rpx;
	    color: #fff;
	  }
	}
	
	page {
		font-weight: normal;
	}

	.overlay-image {
		width: 95%;
		height: 90%;
	}

	.multi-line-ellipsis {
		color: #fff;
		padding: 5rpx 10rpx;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.text-style {
		width: 92%;
		margin: 15rpx auto;
	}

	.content {
		background-color: #292929;
		height: 100vh;
		overflow-y: auto;
	}

	.head {
		background-color: #29d3b4;
		width: 100%;
	}

	.head-img {
		display: flex;
		align-items: center;
		padding: 10rpx 20rpx;
	}

	.head-text {
		color: #fff;
		font-size: 35rpx;
		padding-left: 20rpx;
	}

	.card {
		width: 100%;
		height: 450rpx;
		position: relative;
	}

	.card-back {
		background-color: #29d3b4;
	}

	.card-backs {
		background-color: #292929;
	}

	.color-style {
		width: 100%;
		height: 50%;
	}

	.card-con {
		width: 92%;
		//height: 92%;
		background-color: #fff;
		border-radius: 20rpx;
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		font-size: 30rpx;
	}

	.card-head {
		display: flex;
		justify-content: space-between;
		padding: 30rpx 20rpx 20rpx;
	}

	.card-head-txt {
		color: #AAAAAA;
	}

	.card-head-txt1 {
		padding-left: 10rpx;
	}

	.card-head-back1 {
		color: #4b4b4b;
	}

	.card-head-back2 {
		color: #2bd3b5;
	}

	.card-con-txt {
		color: #AAAAAA;
		padding: 5rpx 20rpx 20rpx;
	}

	.card-con-txt1 {
		display: flex;
		justify-content: space-between;
		padding: 20rpx 20rpx 0;
		height: 220rpx;
	}

	.card-con-txt1-left {
		width: 42%;
		height: 100%;
		position: relative;
	}

	.card-con-txt1-left-txt {
		font-size: 32rpx;
		color: #29d3b4;
		position: absolute;
		left: 50%;
		transform: translate(-50%, -50%);
	}

	.top {
		top: 60%;
	}

	.top1 {
		top: 80%;
	}

	.card-con-txt1-right {
		width: 58%;
		height: 100%;
	}

	.more {
		padding: 0 30rpx 30rpx;
		text-align: right;
		color: #F59A23;
	}

	.upcomin-classes {
		background-color: #292929;
		width: 100%;
		height: 136rpx;
	}

	.upcomin-classes-div {
		padding-top: 20rpx;
		width: 92%;
		background-color: #29d3b4;
		height: 106rpx;
		margin: auto;
		border-radius: 50rpx;
	}

	.upcomin-classes-div-con {
		display: flex;
		align-items: center;
		color: #fff;
	}

	.upcomin-classes-div-con-left {
		width: 60rpx;
		margin-left: 80rpx;
		text-align: right;
	}

	.upcomin-classes-div-con-centre {
		width: 2rpx;
		height: 60rpx;
		background-color: #fff;
		margin-left: 25rpx;
	}

	.upcomin-classes-div-con-right {
		width: 100rpx;
		height: 50rpx;
		background-color: #32baa1;
		text-align: center;
		line-height: 50rpx;
		border-radius: 50rpx;
		margin-left: 80rpx;
	}

	.after-class {
		background-color: #292929;
		width: 100%;
		height: auto;
	}

	.after-class-title {
		width: 92%;
		display: flex;
		justify-content: space-between;
		margin: auto;
	}

	.after-class-title-left {
		color: #fff;
		font-size: 35rpx;
		border-bottom: 4rpx #29d3b4 solid;
	}

	.after-class-title-right {
		color: #F59A23;
		font-size: 30rpx;
	}

	.after-class-con {
		width: 92%;
		height: 246rpx;
		background-color: #404045;
		border-radius: 20rpx;
		margin: 15rpx auto;
		display: flex;
		align-items: center;
	}

	.after-class-con-txt {
		display: flex;
		justify-content: space-between;
		padding: 20rpx;
		height: 95%;
		width: 100%;
		align-content: space-around;
	}
	
	.pic {
		width: 144rpx;
		height: 144rpx;
		border-radius: 50%;
	}
</style>