
<template>
  <view class="page">
    <cu-custom :isBack="false"></cu-custom>
    <view class="header" :style="[{top:topHeader + 'px'}]">
			 <view class="header-box flex justify-end">
						<view class="header-title">
							<view class="header-title-main">
									<view class="margin-bottom-xs">选课</view>
									<view class="point"></view>
							</view>
						</view>
						<view class="header-search flex-sub">
							 <view class="flex justify-between">
								 	<input type="text" v-model="params.course_name" class="header-search-input flex-sub" placeholder="搜索课程" @confirm="search">
							 		<text class="cuIcon-search text-gray header-search-icon" @tap="search"></text>
							 </view>
						</view>
			 </view>
		</view>
		<scroll-view :scroll-y="true" :refresher-enabled="true" class="scroll-main"
		:refresher-triggered="triggered"
		:style="[{height:'calc(100vh - 102px - '+ topHeader+'px)'}]"
		@refresherrefresh="onRefresh" @scrolltolower="loadMore">
			<view class="main">
				<view class="main-title">活动和餐饮</view>
				<view class="flex justify-around course">
					<course v-for="(item,index) in courses" :key="index"
					@tap="goCourse(item.type)"
					:course="item" class="course-item flex-sub margin-xs"></course>
				</view>
				<view class="main-title margin-top-xs">一键报班</view>
				<view class="apply-class flex">
					<image mode="widthFix"  @tap="goGift" src="/static/imgs/index/baoban.png" class="flex-sub apply-class-img margin-xs"/>
				</view>
				<view class="recommend margin-top-xs">
					<view class="recommend-title">推荐课程</view>
					<view class="recommend-filter margin-top-xs flex">
							<view class="filter-item text-center flex-sub" @tap="sort('home')" :class="{'text-sort':sortCur==='home'}">综合</view>
							<view class="filter-item text-center flex-sub" @tap="sort('sales')" :class="{'text-sort':sortCur==='sales'}">销量
								<image mode="widthFix" class="sort-icon" :src="sortCur==='sales'?(sortItem.sales===0?sortIcons.up:sortIcons.down):sortIcons.no"></image>
							</view>
							<view class="filter-item text-center flex-sub" @tap="sort('money')" :class="{'text-sort':sortCur==='money'}">价格
								<image mode="widthFix" class="sort-icon" :src="sortCur==='money'?(sortItem.money===0?sortIcons.up:sortIcons.down):sortIcons.no"></image>
							</view>
							<view class="filter-item text-center flex-sub">{{grade_now}}</view>
							<view class="filter-item text-right flex-sub" @tap="showModal" data-target="FilterModal">筛选
								<text class="cuIcon-filter text-gray"></text>
							</view>
					</view>
					<view class="list">
							<view class="cu-card" v-for="(item,index) in list" :key="index">
								<view class="cu-item">
									<card :item="item"></card>
								</view>
							</view>
					</view>
				</view>
			</view>
		</scroll-view>
    <view class="cu-modal drawer-modal justify-end" :class="modalName=='FilterModal'?'show':''" @tap="hideModal">
      <view class="cu-dialog basis-lg" @tap.stop=""
        :style="[{top:topHeader+'px',height:'calc(100vh - ' + topHeader + 'px)'}]">
					<view class="filter-title">机构筛选</view>
				  <view class="btn-check-group padding-lr">
						<checkbox-group @change="checkboxChange" class="flex" style="flex-wrap: wrap;" id="agency">
							<label class="btn-check-label margin-top-sm padding-lr-xs text-sm text-ellipsis" :class="{'bg-cyan':params.agency.includes(item.id+'')}"
								v-for="item in filters.agency" :key="item.id">
								<checkbox :value="item.id"/>
								{{item.name}}
							</label>
						</checkbox-group>
        	</view>
					<view class="filter-title">周期筛选</view>
					<view class="btn-check-group padding-lr">
						<checkbox-group @change="checkboxChange" class="flex" style="flex-wrap: wrap;" id="day">
							<label class="btn-check-label margin-top-sm padding-lr-xs text-sm" :class="{'bg-cyan':params.day.includes(index+'')}"
								v-for="(item,index) in filters.week" :key="index">
								<checkbox :value="index"/>
								{{item}}
							</label>
						</checkbox-group>
        	</view>
					<view class="filter-title">价格区间（元）</view>
					<view class="btn-check-group padding-lr">
						<radio-group  class="flex" style="flex-wrap: wrap;" id="price">
							<label class="btn-check-label margin-top-sm padding-lr-xs text-sm" :class="{'bg-cyan':params.price===item.name}"
								 v-for="item in filters.price_list" :key="item.id" @tap="radioChange(item.name)">
								<radio :value="item.name"/>
								{{item.name}}
							</label>
						</radio-group>
        	</view>
					<view class="padding-lr">
							<button class="check-course cu-btn bg-cyan margin-tb-sm button-hover" @tap="check_course">确定</button>
					</view>
      </view>
    </view>
    <mp-tabbar :outerSelected="0" />
  </view>
</template>

<script>
import course from './components/course.vue'
import card from './components/card.vue'
import { _optionCourse, _filter } from '@/api/course'
import { filterParams } from '@/common/utils/tool'
import { mapGetters } from 'vuex'
export default {
  components: {
    course, card
  },
  data () {
    return {
      topHeader: this.globalCustomBarHeight,
      modalName: '',
      triggered: false,
      grade_now: '年级',
      sortCur: 'home', // 当前排序
      filters: {},
      sortIcons: {
        no: '/static/imgs/index/xiaoshou_shaixuan.png',
        up: '/static/imgs/index/xiaoshou_shaixuan1.png',
        down: '/static/imgs/index/xiaoshou_shaixuan2.png'
      },
      sortItem: {
        home: 0,
        sales: 0,
        money: 0
      },
      courses: [// 排序情况
        {
          applying: true,
          back: '/static/imgs/index/zmk.png',
          background: '#5FCFE0',
          ch: '选课',
          en: 'Course',
          type: 0
        },
        {
          applying: true,
          back: '/static/imgs/index/hdk.png',
          background: '#f8be32',
          ch: '活动',
          en: 'Activity',
          type: 2
        },
        {
          applying: false,
          back: '/static/imgs/index/zmk.png',
          background: '#67d2a9',
          ch: '报餐',
          en: 'Catering',
          type: 1
        }
      ],
      price: [],
      params: {
        page_num: 1,
        course_name: '',
        agency: [],
        day: [],
        price: '',
        sort: '',
        list_type: 0// 0 课程,1 餐饮,2活动
      },
      init: { // 初始化
        page_num: 1,
        course_name: '',
        agency: [],
        day: [],
        price: '',
        sort: '',
        list_type: 0// 0 课程,1 餐饮,2活动
      },
      list: [],
      noMore: false, // 还有没
      originList: {}
    }
  },
  computed: {
    ...mapGetters([
      'kid', 'token'
    ])
  },
  onShow() {
    // 登录后才进入后续操作
    this.checkLogin().then(res => {
      if (res) {
        if (!this.kid) {
          return this.globalNavigateTo('myStudents')
        }
        this.params = Object.assign({}, this.init)
        this.get_list(true)// true初始化加载过滤项
      }
    })
  },
  methods: {
    checkLogin() {
      return new Promise((resolve, reject) => {
        if (this.token) { // 跳转至登录页
          resolve(true)
        } else {
          uni.showModal({
            title: '请先登录',
            content: '您还没有登录,请先去登录',
            success: res => {
              if (res.confirm) {
                uni.navigateTo({ url: '/pages/login/index' })
              }
            }
          })
          resolve(false)
        }
      })
    },
    goCourse(type) {
      this.params.list_type = type
      this.search()
    },
    loadFilter() { // 加载筛选项
      const params = {}
      _filter(params).then(res => {
        this.filters = res.data
        this.courses[1].applying = this.filters.is_activity
        this.courses[2].applying = this.filters.is_catering
      })
    },
    showModal (e) {
      this.modalName = e.currentTarget.dataset.target
    },
    hideModal (e) {
      this.modalName = null
    },
    radioChange(v) {
      if (this.params.price === v) { // 选中取消
        this.params.price = null
      } else { // 空则赋值
        this.params.price = v
      }
    },
    checkboxChange(e) {
      const type = e.target.id
      const values = e.detail.value
      switch (type) {
        case 'agency':
          this.params.agency = values
          break
        case 'day':
          this.params.day = values
          break
        case 'price':
          // this.params.price = values
          break
        default:
          console.log('error')
      }
    },
    search() { // 搜索课程
      this.params.page_num = 1
      this.get_list()
    },
    check_course() { // 筛选课程
      this.params.page_num = 1
      this.get_list()
      this.hideModal()
    },
    onRefresh() { // 下拉刷新
      this.triggered = true
      this.params.page_num = 1
      this.params.list_type = 0
      this.get_list()
      setTimeout(() => {
        this.triggered = false
      }, 1000)
    },
    loadMore() {
      if (this.noMore) {
        uni.showToast({ title: '暂无更多课程数据', icon: 'none' })
        return false
      }
      this.params.page_num++
      this.get_list()
    },
    sort(type) { // 排序搜索
      const sorts = {
        home: 0,
        sales: 0,
        money: 0
      }
      if (type === this.sortCur) {
        const sortOrder = this.sortItem[type]
        sorts[type] = sortOrder > 0 ? 0 : 1
      } else {
        this.sortCur = type
      }
      const order = sorts[type] > 0 ? 'desc' : 'asc'
      this.sortItem = sorts
      this.params.sort = type + '_' + order
      this.params.page_num = 1
      this.get_list()
    },
    get_list(init = false) {
      let params = Object.assign({}, this.params)
      params = filterParams(params)
      if (params.day.length > 0) {
        params.day = JSON.stringify(params.day)
      }
      if (params.agency.length > 0) {
        params.agency = JSON.stringify(params.agency)
      }
      _optionCourse(params).then(res => {
        if (params.page_num > 1) {
          if (res.data.length < this.page_size) this.noMore = true
          this.list = this.list.concat(res.data)
        } else {
          this.noMore = false
          this.list = res.data
          if (this.list && this.list.length > 0) {
            this.grade_now = this.list[0].grade_now
          }
        }
        // 初始化加载过滤项
        if (init) this.loadFilter()
      })
    },
    goGift() {
      this.globalNavigateTo('classGift', { package_id: 0 })
    }
  }
}
</script>

<style lang="scss">
@import '~@/common/css/mixin.scss';
.page{
 height:100vh;
}
.scroll-main{
	margin-top:54px;
}
.header{
	position:fixed;
	height:54px;
	left:0;
	right:0;
	z-index:999;
	padding:20rpx;
	background:#fff;
	&-box{
		align-items: center;
	}
	&-search{
		margin-left:60rpx;
		align-items: center;
		&-input{
			background: #ededed;
    	border-radius: 999em;
			padding-left:30rpx;
      line-height:32px;
			height:32px;
    	font-size: 14px;
		}
		&-icon{
			margin:0 30rpx;
			line-height:32px;
			font-size:24px;
		}
	}
}
.main{
	padding:20rpx;

}
.main-title{
  font-size: 12px;
  margin-bottom: 10px;
  color: #999;
}
.search-box{
	margin-left:20rpx;
}
.course-item{
  border-radius: 10px;
  color: #fff;
}
.recommend{
	&-title{
		@include title(10px,18px);
	}
	&-filter{
		.filter-item{
			position:relative;
		}
	}
	.sort-icon{
		margin-left:6rpx;
		width:15rpx;
	}
}
.btn-check-group {
  checkbox {
    display: none;
  }
	radio{
		display:none;
	}
  label {
    display: inline-block;
		margin-right:10rpx;
    position: relative;
		padding:0 20rpx;
    line-height: 30px;
    border-radius: 100rpx;
    flex-wrap: nowrap;
    border: 1px solid #eee;
  }
}
.filter-title{
	padding-left:30rpx;
	margin-top:10px;
	text-align:left;
	@include title(0,14px)
}
.check-course{
	width:100%;
}
.cu-modal.drawer-modal .cu-dialog{
	min-width:300rpx;
}
.cu-card>.cu-item{
	margin:10rpx;
}
</style>
