<template>
  <div>
    <div style="display: flex;justify-content:space-between; padding: 12px 32px 10px 22px;">
      <div style="display: flex;justify-content: flex-start;">
        <div>
          <el-select v-model="courseType" clearable placeholder="类型">
            <el-option label="全部" value='1'></el-option>
            <!-- <el-option label="微课" :value="10"></el-option> -->
            <el-option label="录播课" :value="20"></el-option>
            <!-- <el-option label="在线课" value="online-course"></el-option> -->
            <!-- <el-option label="面授课" value="face-course"></el-option>
            <el-option label="学习项目" value="project"></el-option> -->
            <el-option label="线下课" :value="30"></el-option>
            <el-option label="学习项目" :value="40"></el-option>
         </el-select>
        </div>
        <el-select style="margin-left:10px" v-model="status" clearable placeholder="学习进度">
          <el-option label="全部" value='0'></el-option>
          <el-option label="未开始" :value="1"></el-option>
          <el-option label="进行中" :value="2"></el-option>
          <el-option label="已完成" :value="9"></el-option>
          <!-- <el-option label="已停用" :value="3"></el-option> -->
        </el-select>
        <div style="padding-left: 10px;"><el-input v-model="params.courseName" clearable placeholder="搜索名称"></el-input></div>
        <div style="padding-left: 10px;"><el-button type="primary" icon="el-icon-search" @click="searchData()">搜索</el-button></div>
        <div style="padding-left: 10px"><el-button type="primary" icon="el-icon-refresh-right" @click="reset()">重置</el-button></div>
      </div>
    </div>
  <div class="uc-list" v-loading="loading">
    <div class="uc-course" v-for="(item,idx) in pageChange" @click="jumpRouter(item)" :key="idx">
      <div class="uc-course-img" style="width: 212px;height:119px">
        <course-image :course="item"></course-image>
      </div>
      <div class="uc-course-info">
        <div class="uc-course-name" style="cursor: pointer;">
          <div>
          <span v-if="item.courseType==10" class="uc-course-type2">录播</span>
          <span v-if="item.courseType==20" class="uc-course-type2">录播</span>
          <span v-if="item.courseType==30" class="uc-course-type3">线下课</span>
          <span v-if="item.courseType==40" class="uc-course-type4">学习项目</span>
          </div>
         <div style="flex:1;">
           <a v-html="$keywordActiveShow(item.courseName,params.courseName)" class="uc-title two-line-ellipsis"></a>
         </div>
        </div>
        <div style="width: 80%;margin-top:38px"><el-progress :percentage="item.progress"></el-progress></div>
        <div class="uc-course-text">报名时间：{{item.addTime}}</div>
      </div>
      <div class="uc-course-btns">
          <div style="text-align: right;">
            <el-button class="del" @click.stop="delItem(item,idx)" type="text" icon="el-icon-delete" size="mini" title="删除"></el-button>
          </div>
          <span  @click.stop="jumpRouter(item)">
            <el-button style="margin-top:30px" v-if="item.progress==0" type="primary" size="small">开始学习</el-button>
            <el-button style="margin-top:30px" v-if="item.progress>0 && item.progress<100" type="primary" size="small">继续学习</el-button>
            <el-button style="margin-top:30px" v-if="item.progress==100" type="primary" size="small">回顾</el-button>
          </span>
      </div>
    </div>
      <div v-if="pageChange.length > 0 " style="text-align: center;margin-top:57px;">
          <el-pagination background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="page.pageIndex"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="page.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="couresList.length">
          </el-pagination>
      </div>
      <div class="list-wu">
        <div v-if="loading">
            <span v-if="dataList.length==0">正在加载数据...</span>
            <span v-else>查询中...</span>
        </div>
        <div v-else >
            <span v-if="dataList.length==0">当前列表无数据</span>
            <span v-else-if="couresList.length==0" >未找到您要搜索的内容</span>
        </div>
      </div>
  </div>
  </div>
</template>

<script>
import studyItem from '@/components/Course/studyItem.vue';
import apicourseStudy  from '@/api/modules/courseStudy.js';
import apiBoeCourse from '@/api/boe/course.js';
import studyImage from '@/components/Course/studyImage.vue';
import courseImage from "@/components/Course/courseImage.vue";
export default {
  name: 'ucStudyCourses',
  components: { studyItem,studyImage,courseImage },
  data() {
    return {
      courseType: '',
      status: '',
      loading: true,
      fileUrl:process.env.VUE_APP_FILE_BASE_URL,
      page: {
        pageIndex: 1,//第几页
        pageSize: 10, // 每页多少条
        count: 0
      },
      dataList: [],//总数据
      isNextPage: false,
      pageIndex:1,
      isListOne: true,
      params: { courseName: '', courseType: '',status:''},
      couresList: [],//显示的数据
      options: [
        {
          value: 1,
          label: '项目'
        },
        {
          value: 2,
          label: '课程',
          children: [
            {
              value: 10,
              label: '微课'
            },
            {
              value: 21,
              label: '录播课'
            }
          ]
        }
      ]
    };
  },
computed: {
   pageChange() {
     let list = this.couresList.slice((this.page.pageIndex -1)* this.page.pageSize,this.page.pageIndex*this.page.pageSize);
     return list;
    },
},
  mounted() {
    // this.searchData();
    // this.getMyLearning()
   this.getData();
  },
  methods: {
  delItem(item,itemIdx){
    this.$confirm('您确定要删除所选课程吗？', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() =>{
            if(item.isOld){
               apiBoeCourse.delLearning(item.kid).then(res=>{
                  if(res.status==200){
                     this.$message({ type: 'success', message: '删除成功!' });
                     this.couresList.splice(itemIdx,1);
                     this.dataList.forEach((it,i)=>{
                       if(item.id == it.id) {
                         this.dataList.splice(i,1);
                       }
                     })
                  } else {
                    this.$message({ type: 'error', message: res.message });
                  }
               });
            }else{
                apicourseStudy.deleteSignUp(item.id,item.courseId).then(res =>{
                  if(res.status==200){
                     this.$message({ type: 'success', message: '删除成功!' });
                     this.couresList.splice(itemIdx,1);
                     this.dataList.forEach((it,i)=>{
                       if(item.id == it.id) {
                         this.dataList.splice(i,1);
                       }
                     })
                  } else {
                     this.$message({ type: 'error', message: res.message });
                  }
                })
            }

      })
  },
  async getData() { //当前方案，此处只是加载一次
      let type = '';
    // if(this.params.courseType){
      if(this.params.courseType==20){
        type='online-course';
      }else if(this.params.courseType==30){
        type='face-course';
      }else if(this.params.courseType==40){
        type='project';
      }
    // }
    // if(this.params.courseType ==20 ){
    // this.params.courseType =  [10,20]
    // }
      this.loading = true;
      let data = {
        type:type,
        page:this.pageIndex,
        size:100
      }
      this.isListOne = true;
      this.params.pageSize = 100;
      this.params.pageIndex = 1;
      let list = this.dataList;
      let clist = this.couresList;
      // Promise.all([apiBoeCourse.myLearning(data),apicourseStudy.myStudyList(this.params)]).then(res=>{
      //   let list = [];
      //   list.push(...res[1].result.list);
      //   res[1].result.list.forEach(item=>{
      //     item.courseImage = this.fileUrl + item.courseImage;
      //   })
      //  let data = this.filterConversion(res[0].result.dataList);
      //  list.push(...data);
      //  this.couresList = list;
      //  this.dataList = list;
      //  this.loading = false;
      // }).catch(err=>{
      //   console.log(err,'err');
      // })
    await apicourseStudy.myStudyList(this.params).then(res =>{
          if(res.status == 200) {
            res.result.list.forEach(item=>{
              if(item.courseImage){
                item.courseImage = this.fileUrl + item.courseImage;
              }
            })
            list.push(...res.result.list);
            clist.push(...res.result.list);
          }else{
            console.log('加载报名数据失败:'+res.message);
          }
          this.loading = false;
      })
    await apiBoeCourse.myLearning(data).then(rs=>{
          if(rs.status == 200) {
            let data = this.filterConversion(rs.result.dataList);
            list.push(...data);
            clist.push(...data);
          }else{
            console.log('加载原报名数据失败:'+rs.message);
          }
          this.loading = false;
      })
    },
    filterConversion(data){
      let list = [];
      data.forEach((item,index)=>{
      let type = null;
      if(item.type=='online-course'){
        type=20;
        }else if(item.type=='face-course'){
          type=30;
        }else if(item.type=='project'){
          type=40;
        }
        let status = null;
        if(item.status == '0') {
          status = 1;
        } else if(item.status == '1') {
          status = 2;
        }else if(item.status == '2') {
          status = 9;
        }
        let num = item.completeProgress.replace('%',"");
        item.completeProgress = Number(num);
        list.push({
          courseImage: item.cover[0].url,
          courseName: item.title,
          courseType: type,
          id: item.id,
          addTime:item.enrollTime,
          progress: item.completeProgress,
          status: status,
          isOld: true,
          kid:item.ms_timeline_kid
        })
      })
      return list;

    },
    jumpRouter(item) {
      if(item.isOld){

        // this.$router.push({path:'/course/boeframe',query:{id:item.id,type:item.courseType}})
        location.href=`${this.webBaseUrl}/course/boeframe?id=${item.id}&type=${item.courseType}`
          //window.open(`${this.webBaseUrl}/course/boeframe?id=${item.id}&type=${item.courseType}`,'_self' )
      } else {
           if(item.courseType==10){
            // let routeData = this.$router.resolve({ path: '/course/micro?id='+item.courseId}); // , query: {  id: 1 }
            // console.log(routeData,'routeData');
            // window.open(this.webBaseUrl+routeData.href, '_blank');
            // window.open('/pc/course/micro?id='+item.courseId,'_blank')
            this.$router.push({path:'/course/micro',query:{id:item.courseId}})
        }
        if(item.courseType==20){
          if(item.progress>0 && item.progress<100) {
            //let routeData = this.$router.resolve({ path: '/course/studyindex?id='+item.courseId}); // , query: {  id: 1 }
            //    console.log(routeData,'routeData');
             //window.open(this.webBaseUrl+routeData.href, '_blank');
            // window.open('/pc/course/studyindex?id='+item.courseId,'_blank')
             this.$router.push({path:'/course/studyindex',query:{id:item.courseId}})
          } else {
             //let routeData = this.$router.resolve({ path: '/course/detail?id='+item.courseId}); // , query: {  id: 1 }
            //    console.log(routeData,'routeData');
            // window.open(this.webBaseUrl+routeData.href, '_blank');
           // window.open('/pc/course/detail?id='+item.courseId,'_blank')
            this.$router.push({path:'/course/detail',query:{id:item.courseId}})
          }
        }
      }


    },
    // getMyLearning() {
    //   let params = {
    //     type:this.params.courseType,
    //     page:this.pageIndex,
    //     size:200
    //   }
    //   apiBoeCourse.myLearning(params).then(res=>{
    //     if(res.status == 200) {
    //        res.result.dataList.forEach(item => {
    //           let num = item.completeProgress.replace('%',"");
    //           item.completeProgress = Number(num);
    //           item.url = item.cover[0].url;
    //        });
    //       //  if(this.page == 1) {
    //          this.dataList = res.result.dataList;
    //       //  } else {
    //       //    this.dataList.push(...res.result.dataList);
    //       //  }

    //        this.isNextPage = res.result.isNextPage;
    //     }
    //   })
    // },
    reset(){
       this.params.courseName = '',
       this.params.courseType = '',
       this.params.status = '';
       this.page.pageIndex = 1;
       this.couresList = this.dataList;
       this.courseType = '';
       this.status = '';
    },
    searchData() {
      this.loading=false;//因为是页面搜索，所以直接设置为false
      this.page.pageIndex = 1;
      this.isListOne = true;
      let list = this.dataList;
      if(this.courseType == '1') {
        this.params.courseType = '';
      } else {
        this.params.courseType = this.courseType;
      }
      let type;
      if(this.params.courseType == 20) {
        type = 10;
      }
      if(this.status == '0') {
        this.params.status = '';
      } else {
        this.params.status = this.status;
      }
     if(this.params.courseType != '') {
           list=  list.filter(item => {
               if(item.courseType === this.params.courseType || item.courseType === type) {
               return item;
             }
            });
      }
      if(this.params.status !== '') {
          list= list.filter(item => {
              if(item.status === this.params.status){
                return item;
              }
            });
      }
      if(this.params.courseName !== '') {
          list=  list.filter(item => {
             return item.courseName.toLowerCase()
                .indexOf(this.params.courseName.toLowerCase()) > -1;
            });
      }
      this.couresList = list;

    },
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.page.pageIndex = 1;
    },
    handleCurrentChange(val) {
     this.page.pageIndex = val;
    },
  }
};
</script>

<style scoped lang="scss">
.uc-title{
  word-break:break-all;
  float: left;
}
.two-line-ellipsis{
 //  display: -webkit-box;
  // white-space:pre-wrap;
  overflow: hidden;
  line-height: 30px;
  text-overflow:ellipsis;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
  box-sizing: border-box;
}
 .del{
      color: #8590A6;
      // margin-left: 70%;
      font-size: 14px;
    }
.uc-list{
  padding-left: 22px;
}
.uc-course-type1{
  width: 58px;
  height: 26px;
  font-size: 14px;
  line-height: 26px;
  text-align: center;
}
.uc-course-type2{
  width: 58px;
  height: 26px;
  font-size: 14px;
  line-height: 26px;
  text-align: center;
}
.uc-course-type3 {
    padding: 3px 15px;
    background: #08a890;
    color: #fff;
    font-size: 14px;
    border-radius: 2px
  }
  .uc-course-type4 {
    width: 58px;
    height: 26px;
    padding: 3px 15px;
    background: #75aefe;
    color: #fff;
    font-size: 14px;
    border-radius: 2px
  }
.list-wu{
  text-align: center;
  font-size: 20px;
  margin-top: 70px;
  color: #ccc;
}
  .is-more{
    margin-top: 10px;
    text-align: center;
    height: 50px;
    span{
      padding: 10px 20px;
      border: 1px solid #ccc;
      border-radius: 20px
    }
  }
.uc-badge {
  margin-top: 10px;
  margin-right: 40px;
}
.uc-course {
  display: flex;
  justify-content: space-around;
  border-bottom: 1px solid #E8E8E8;
  margin-right: 32px;
  padding: 20px 0px 15px  0px ;
  cursor: pointer;
  .uc-course-img {
    width: 200px;
    img {
      width: 200px;
      border: 1px solid #f4f4f5;
    }
  }
  .uc-course-info {
    flex: 1;
    margin-top: -3px;
    line-height: 28px;
    padding: 0px 10px;
    .uc-course-name {
      display: flex;
      span{
        width: 58px;
        height: 26px;
        margin-right: 8px;
      }
      font-size: 18px;
      font-weight: 700;
      color: #333;
    }
    .uc-course-text {
      color: #666;
      font-size: 14px;
      margin-top: 19px;
    }
  }
  .uc-course-btns {
    // width: 150px;

  }
}
</style>
