<template>
  <div class="student_detail">
    <div class="infomation">
      <div class="top">
        <div class="info">
          <img class="head" :src="defaultHead" alt="" />
          <div class="right">
            <p class="name">
              {{ studentInfo.travelerName }}<span @click="showPicker = true"> <van-icon name="exchange" /> 切换学生 </span>
            </p>
            <p class="school_name">
              {{ studentInfo.schoolName }}<span v-if="studentInfo.enrollYear">·{{ studentInfo.enrollYear }}级</span>
            </p>
          </div>
        </div>
        <HomeScan type="2"></HomeScan>
      </div>
      <div class="count_box">
        <div class="count_item">
          <p class="count">
            <span>{{ signCheckCountInfo.signCount }}</span
            >/次
          </p>
          <p class="des">基地打卡次数</p>
        </div>
        <div class="line"></div>
        <div class="count_item">
          <p class="count">
            <span>{{ signCheckCountInfo.courseDays }}</span
            >/天
          </p>
          <p class="des">课程实践</p>
        </div>
      </div>
      <div class="icon_box">
        <div class="icon_item" @click="handleYanxue">
          <img src="@/assets/grow_up/icon1.png" alt="" />
          <p>研学码</p>
        </div>
        <div class="icon_item" @click="handleMyAlbum">
          <img src="@/assets/grow_up/icon2.png" alt="" />
          <p>我的相册</p>
        </div>
        <div class="icon_item" @click="handleRelease">
          <img src="@/assets/grow_up/icon3.png" alt="" />
          <p>我的游记</p>
        </div>
      </div>
    </div>
    <div class="list_box">
      <div class="line" v-if="RecordList.length > 0"></div>
      <van-list
        v-if="RecordList.length > 0"
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :immediate-check="false"
        @load="getGrowthRecord"
      >
        <div class="list_item" v-for="(item, index) in RecordList" :key="index">
          <div class="point"></div>
          <div class="right">
            <div class="item_top">
              <p class="day">{{ item.day }}</p>
              <div>
                <p class="week">{{ item.week }}</p>
                <p class="time">{{ item.time }}</p>
              </div>
            </div>
            <div class="item_bottom">
              <img v-if="item.url" :src="item.url" alt="" />
              <!-- type (string, optional): 1-签到 2-参加活动 3-发布内容 , -->
              <p class="item_title" v-if="item.type == 1"><span class="type">基地签到</span> {{ item.title }}</p>
              <p class="item_title" v-if="item.type == 2"><span class="type">参加了</span> {{ item.title }}</p>
              <p class="item_title" v-if="item.type == 3 && item.title">
                <span class="type">发布了</span> {{ item.title }}<span class="type">动态</span>
              </p>
              <p class="item_title" v-if="item.type == 3 && !item.title"><span class="type">发布了一条最新动态</span></p>
              <span class="btn" v-if="item.type == 3" @click="handleGrowUpDetail(item)">查看详情</span>
            </div>
          </div>
        </div>
      </van-list>
      <van-empty v-if="RecordList.length == 0" :image="require('@/assets/empty.png')" description="暂无记录" />
    </div>
    <!-- 选择学生 -->
    <van-popup v-model="showPicker" round position="bottom">
      <van-picker :columns="childList" value-key="travelerName" show-toolbar @cancel="showPicker = false" @confirm="onConfirm" />
    </van-popup>
    <!-- 学校认证 -->
    <van-popup style="background: transparent" get-container="body" v-model="showAddChildPopupGroup">
      <AddChildPopupGroup
        v-if="showAddChildPopupGroup"
        @complete="complete"
        :step="step"
        :travelerNum="travelerNum"
        :editInfo="editInfo"
      ></AddChildPopupGroup>
    </van-popup>
    <Tabbar active="grow"></Tabbar>
  </div>
</template>
<script>
import AddChildPopupGroup from '@/views/Home/component/AddChildPopupGroup'
import HomeScan from '@/views/Home/component/HomeScan'
import Tabbar from '@/components/c_Tabbar.vue'
export default {
  data() {
    return {
      defaultHead: require('@/assets/head.png'),
      studentInfo: '',
      signCheckCountInfo: '', //打卡和课程天数信息
      showPicker: false,
      childList: [],
      RecordList: [], //记录
      pageNum: 1,
      pageSize: 5,
      loading: false,
      finished: false,
      showAddChildPopupGroup: false, //学校认证弹出框
      travelerNum: '',
      step: '',
      editInfo: '',
      unionId: '',
      appId:'wx1305e88d2bc74073'
    }
  },
  mounted() {
    sessionStorage.setItem('prePage', 'GrowUpRecord')
    sessionStorage.setItem('prePageQuery', '{}')
    if (process.env.NODE_ENV === 'production' && this.common.isWeiXin()) {
      let openId = sessionStorage.getItem('openId')
      if (!openId) {
        this.$router.push({ name: 'Authorize'})
        return
      }
      this.unionId = sessionStorage.getItem('unionId')
      this.getUserInfo()
    } else {
      this.unionId = this.TestUnionId
      this.getUserInfo()
    }
    // this.getStudentInfo()
  },
  methods: {
    getStudentInfo() {
      let studentInfo = sessionStorage.getItem('StudentDetialInfo')
      let userInfo = sessionStorage.getItem('userInfo')
      let schoolNamesChoose = sessionStorage.getItem('schoolNamesChoose') ? JSON.parse(sessionStorage.getItem('schoolNamesChoose')) : ''
      if (!userInfo) {
        this.$toast.fail('学生信息缺失，请返回首页重试')
        return
      } else {
        userInfo = JSON.parse(userInfo)
        this.childList = userInfo?.subUsers
      }
      let subUsers = userInfo?.subUsers

      if (studentInfo) {
        // 先判断是否有已选择学生信息
        this.studentInfo = JSON.parse(studentInfo)
      } else if (schoolNamesChoose) {
        //再判断是否有一选择学校
        for (let i in subUsers) {
          console.log(subUsers[i].schoolName, schoolNamesChoose)
          if (schoolNamesChoose.schoolName == subUsers[i].schoolName) {
            this.studentInfo = subUsers[i]
            sessionStorage.setItem('StudentDetialInfo', JSON.stringify(this.studentInfo))
            break
          }
        }
        // 如果还是没有对应学校，默认选中第一个
        if (!this.studentInfo) {
          this.studentInfo = subUsers[0]
          sessionStorage.setItem('StudentDetialInfo', JSON.stringify(subUsers[0]))
        }
      } else {
        this.studentInfo = subUsers[0]
        sessionStorage.setItem('StudentDetialInfo', JSON.stringify(this.studentInfo))
      }
      console.log(this.studentInfo)
      this.$nextTick(() => {
        this.initPage()
      })
    },
    initPage() {
      this.getSignCheckCountInfo() //根据用户编号获取打卡和课程天数信息
      this.getGrowthRecord() //成长记录
    },

    // 根据用户编号获取打卡和课程天数信息
    getSignCheckCountInfo() {
      this.yxAxios
        .get(`${this.yanxueUrl}/api/StudiesWap/SignCheckCountInfo/ByUserId?userId=${this.studentInfo?.travelerNum}`)
        .then((res) => {
          this.$toast.clear()
          console.log('天数：', res.data)
          if (res.data.status == 1) {
            this.signCheckCountInfo = res.data.data
          } else {
            this.$toast.fail(res.data.message)
          }
        })
    },
    // 成长记录
    getGrowthRecord() {
      this.yxAxios
        .post(`${this.proxyUrl}/api/growth/content/getGrowthRecord`, {
          tripNo: this.studentInfo.travelerNum,
          pageNum: this.pageNum,
          pageSize: this.pageSize,
        })
        .then((res) => {
          if (res.data.code == 200) {
            this.loading = false
            if (res.data.total < this.pageNum * this.pageSize) {
              this.finished = true
            } else {
              this.pageNum++
            }
            let RecordList = res.data.rows
            var weekArr = ['一', '二', '三', '四', '五', '六', '日']
            for (let i in RecordList) {
              let week = this.Moment(RecordList[i].ctime).isoWeekday()
              RecordList[i].week = '星期' + weekArr[week - 1] //星期
              RecordList[i].day = this.Moment(RecordList[i].ctime).date()
              RecordList[i].time = this.Moment(RecordList[i].ctime).format('YYYY/MM')
            }
            this.RecordList = this.RecordList.concat(res.data.rows)
          } else {
            this.$toast(res.data.message)
          }
        })
    },
    // 切换学生
    onConfirm(item) {
      console.log(item)
      this.pageNum = 1
      this.RecordList = []
      this.finished = false
      this.studentInfo = item
      this.showPicker = false
      sessionStorage.setItem('StudentDetialInfo', JSON.stringify(item))
      this.$nextTick(() => {
        this.initPage()
      })
    },
    // 研学码
    handleYanxue() {
      this.$router.push({ name: 'YanxueCode' })
    },
    // 点击我的相册
    handleMyAlbum() {
      this.$router.push({ name: 'MyAlbum' })
    },
    // 我的游记
    handleRelease() {
      this.$router.push({ name: 'MyStory' })
    },
    // 学校认证完成
    complete() {
      this.showAddChildPopupGroup = false
      this.getChildList()
    },
    // 获取孩子列表
    getChildList() {
      this.$toast.loading({
        message: '加载中...',
        duration: 0,
        forbidClick: true,
      })
      let userInfo = sessionStorage.getItem('userInfo')
      userInfo = JSON.parse(userInfo)
      this.yxAxios.get(`${this.proxyUrl}/user/info/getPortalUserByNum?userNum=${userInfo?.centerNo}`).then((res) => {
        this.$toast.clear()
        if (res.data.code == 200) {
          const userInfo = res.data.data.userInfo
          this.userInfo = userInfo
          sessionStorage.setItem('userInfo', JSON.stringify(userInfo))
          this.childList = userInfo.subUsers
        }
      })
    },
    //查看发布内容详情
    handleGrowUpDetail(item) {
      // contentType (string, optional): 1-用户 2-基地 ,
      this.$router.push({ name: 'GrowUpDetail', query: { id: item.id, type: item.contentType } })
    },
    // 获取用户信息
    getUserInfo() {
      let userInfo = sessionStorage.getItem('userInfo')
      if (userInfo) {
        userInfo = JSON.parse(userInfo)
        this.getStudentInfo()
      } else {
        this.$toast.loading({
          message: '加载中...',
          duration: 0,
          forbidClick: true,
        })
        this.yxAxios.get(`${this.proxyUrl}/api/wx/${this.appId}/getUserInfo?unionId=${this.unionId}`).then((res) => {
          this.$toast.clear()
          if (res.data.data) {
            sessionStorage.setItem('userInfo', JSON.stringify(res.data.data))
            this.userInfo = res.data.data
            this.getStudentInfo()

            if (res.data.data.schoolNames || res.data.data.schoolNames == [] || res.data.data.schoolNames == 'null') {
              sessionStorage.setItem('schoolNames', JSON.stringify(res.data.data.schoolNames))
              this.$store.commit('changeSchool', res.data.data.schoolNames)
              if (!sessionStorage.getItem('schoolNamesChoose')) {
                sessionStorage.setItem('schoolNamesChoose', JSON.stringify(res.data.data.schoolNames[0]))
              }
            } else {
              sessionStorage.setItem('schoolNames', [])
              this.$store.commit('changeSchool', [])
            }
          } else {
            this.checkLogin()
          }
        })
      }
    },
    // 判断是否已登录
    checkLogin() {
      if (process.env.NODE_ENV != 'production') return true
      const userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
      if (!userInfo?.phone) {
        sessionStorage.setItem('prePage', 'GrowUpRecord')
        this.$router.push({ name: 'LoginPublic' })
        return false
      }
      return true
    },
  },
  components: {
    HomeScan,
    AddChildPopupGroup,
    Tabbar,
  },
}
</script>
<style lang="scss" scoped>
.student_detail {
  height: 100%;
  background: rgb(247, 247, 251);
  padding-bottom: 196px;
  box-sizing: border-box;
  .infomation {
    width: 100%;
    height: 852px;
    background: url('~@/assets/home/bg_stu.png');
    background-size: 100%;
    background-position: center;
    .top {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      justify-content: space-between;
      padding: 40px 28px;
      .info {
        display: flex;
      }
      .head {
        width: 96px;
        height: 96px;
        border-radius: 50%;
        overflow: hidden;
      }
      .right {
        width: 450px;
        height: 96px;
        margin-left: 24px;
        display: flex;
        align-content: space-around;
        flex-wrap: wrap;
        // color: #fff;
        .name {
          font-size: 34px;
          font-weight: bold;
          width: 100%;
          span {
            display: inline-block;
            padding: 0 14px;
            margin-left: 14px;
            line-height: 34px;
            border-radius: 17px;
            font-size: 22px;
            background: #24d4ba;
            vertical-align: middle;
            color: #fff;
          }
        }
        .school_name {
          font-size: 26px;
        }
      }
    }
    .count_box {
      display: flex;
      align-items: center;
      justify-content: space-around;
      padding: 0 24px;
      margin-top: 30px;
      .count_item {
        color: #556191;
        text-align: center;
        .count {
          font-size: 24px;
          span {
            font-size: 38px;
            font-weight: bold;
            margin-right: 6px;
          }
        }
        .des {
          margin-top: 14px;
          font-size: 28px;
        }
      }
      .line {
        width: 4px;
        height: 48px;
        background: #fff;
      }
    }
    .icon_box {
      display: flex;
      align-items: center;
      justify-content: space-around;
      width: 702px;
      height: 158px;
      background: #ffffff;
      border-radius: 16px;
      margin: 0 auto;
      margin-top: 30px;
      .icon_item {
        text-align: center;
        img {
          width: 64px;
        }

        p {
          font-size: 26px;
        }
      }
      .line {
        width: 4px;
        height: 48px;
        background: #fff;
      }
    }
  }
  .list_box {
    width: 702px;
    margin: 0 auto;
    margin-top: -340px;
    overflow: hidden;
    border-radius: 16px;
    background: #fff;
    position: relative;
    padding-bottom: 100px;
    .list_item {
      position: relative;
      padding: 45px 0;
      &:first-of-type {
        margin-top: 20px;
      }
      .item_top {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        .day {
          font-size: 32px;
          margin-right: 16px;
        }
        .time,
        .week {
          font-size: 28px;
          line-height: 40px;
        }
      }

      .point {
        display: inline-block;
        width: 16px;
        height: 16px;
        background: #ffffff;
        border: 2px solid #e5e5e5;
        border-radius: 50%;
        margin-left: 32px;
        vertical-align: top;
      }
      .right {
        display: inline-block;
        width: 590px;
        margin-left: 32px;
      }
      .item_bottom {
        background: #f9f9f9;
        position: relative;
        display: flex;
        margin-top: 24px;
        img {
          width: 102px;
          height: 102px;
          border-radius: 16px;
        }
        .item_title {
          font-size: 26px;
          padding: 8px 16px;
          .type {
            color: #999;
          }
        }
        .btn {
          position: absolute;
          bottom: -50px;
          right: 0;
          color: #21a3ff;
          font-size: 26px;
        }
      }
    }
    .line {
      width: 1px;
      height: 100%;
      position: absolute;
      top: 53px;
      left: 40px;
      background: #e5e5e5;
    }
  }
}
</style>
