<template>
  <el-row>
    <el-row>
      <el-form ref="searchForm" :model="searchForm" label-width="80px">
        <search-white-board @search="list">
          <div slot="base">
            <el-row style="line-height: 40px; text-align: right;">
              <!-- <el-col :span="2"><label class="search-label">机构</label></el-col>
              <el-col :span="5">
                <select-organ v-model="searchForm.organIds" />
              </el-col> -->
              <el-col :span="2" :offset="1"><label class="search-label">课程名称</label></el-col>
              <el-col :span="5"><el-input v-model.trim="searchForm.name" placeholder="请输入课程名称" clearable /></el-col>
              <el-col :span="2" :offset="1"><label class="search-label">课程类型</label></el-col>
              <el-col :span="5">
                <el-select v-model="searchForm.type" placeholder="请选择课程类型" style="width: 100%;" @change="list">
                  <el-option v-for="item in constants.OPEN_COURSE_TYPE_LIST" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-col>
            </el-row>
          </div>

          <div slot="more">
            <el-row style="line-height: 40px; text-align: right;">
              <el-col :span="2"><label class="search-label">学年</label></el-col>
              <el-col :span="5">
                <select-school-year v-model="searchForm.schoolYear" clearable filterable @change="list" />
              </el-col>
              <el-col :span="2" :offset="1"><label class="search-label">学期</label></el-col>
              <el-col :span="5">
                <select-semester v-model="searchForm.semester" clearable filterable @change="list" />
              </el-col>
              <el-col :span="2" :offset="1"><label class="search-label">学校</label></el-col>
              <el-col :span="5">
                <select-school v-model="searchForm.schoolId" :clearable="true" :filterable="true" @change="searchChangeSchool" />
              </el-col>
            </el-row>
            <el-row style="line-height: 40px; text-align: right;">
              <el-col :span="2"><label class="search-label">是否删除</label></el-col>
              <el-col :span="5" style="text-align: left;">
                <el-switch v-model="searchForm.isDel" active-color="#13ce66" inactive-color="#ff4949" @change="list" />
              </el-col>
            </el-row>
          </div>
        </search-white-board>
      </el-form>
    </el-row>

    <el-row>
      <white-board>
        <el-tabs v-model="activeName" type="card" @tab-click="list">
          <el-tab-pane label="表格" name="1">
            <el-row>
              <el-col :span="2" :offset="22" style="text-align: right;">
                <el-button icon="el-icon-plus" type="success" plain @click="handleAdd">新增</el-button>
              </el-col>
            </el-row>

            <el-row style="padding: 10px 0px;">
              <el-table :data="tableData" style="width: 100%;" highlight-current-row stripe>
                <el-table-column label="标识" width="160" fixed>
                  <template slot-scope="scope">
                    <el-button type="text" @click="openOrderItemView(scope.row)">{{ scope.row.id }}</el-button>
                  </template>
                </el-table-column>
                <el-table-column prop="organName" label="机构名称" show-overflow-tooltip />
                <el-table-column prop="schoolYear" label="学年" width="50" fixed />
                <el-table-column prop="semester" label="学期" width="50" fixed />
                <el-table-column prop="schoolName" label="学校" show-overflow-tooltip fixed />
                <el-table-column label="年级名称" width="110" fixed>
                  <template slot-scope="scope">{{ scope.row.gradeName | formatGradeNameList }}</template>
                </el-table-column>
                <el-table-column prop="name" label="课程名称" width="200" fixed />
                <el-table-column label="课程价格" width="100" fixed>
                  <template slot-scope="scope">
                    <el-tag type="warning">{{ scope.row.price | moneyFormat }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="课程类型" width="100">
                  <template slot-scope="scope">
                    <course-type :type="scope.row.type" />
                  </template>
                </el-table-column>
                <el-table-column prop="openCourseNumber" label="开班人数" width="70" />
                <el-table-column prop="freeCourseNumber" label="空闲人数" width="70" />
                <el-table-column label="上课时间" width="100">
                  <template slot-scope="scope">
                    <label>每周{{ scope.row.cycle }}</label><br>
                    <label>{{ scope.row.hours }}</label>
                  </template>
                </el-table-column>
                <el-table-column label="报名时间" width="135">
                  <template slot-scope="scope">
                    {{ scope.row.signUpStartTime }}
                    {{ scope.row.signUpEndTime }}
                  </template>
                </el-table-column>
                <el-table-column prop="remarks" label="备注" show-overflow-tooltip />
                <el-table-column label="更新时间" width="135">
                  <template slot-scope="scope">
                    <el-row>{{ scope.row.updateByName }}</el-row>
                    <el-row>{{ scope.row.updateAt }}</el-row>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="240" fixed="right">
                  <template slot-scope="scope">
                    <!-- <el-button type="primary" plain @click="isShowCommentDrawer = true">查看评论</el-button> -->
                    <el-button type="primary" plain @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button v-if="scope.row.isDel" type="success" plain @click="handleIsDel(scope.$index, scope.row)">启用</el-button>
                    <el-button v-if="!scope.row.isDel" type="danger" plain @click="handleIsDel(scope.$index, scope.row)">停用</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-row>

            <el-row>
              <el-pagination :current-page="searchForm.page" :page-sizes="[10, 20, 50, 100]" :page-size="50" layout="total, sizes, prev, pager, next, jumper" :total="total" small @size-change="changeSizeChange" @current-change="changeCurrentChange" />
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="日历" name="2">
            <full-calendar2 :events="timetableData" locale="en" />
          </el-tab-pane>
        </el-tabs>
      </white-board>
    </el-row>

    <el-dialog :visible.sync="dialogVisible" width="80%">
      <label slot="title" style="float: left;">{{ dialogTitle }}</label>

      <el-form ref="form" :model="form" :rules="formRules" label-suffix="：" label-width="80px">
        <el-divider content-position="left">课程</el-divider>
        <el-row>
<!--           <el-row>
            <el-col :span="10" :offset="1">
              <el-form-item label="机构" prop="organId">
                <select-organ v-model="form.organId" :multiple="false" />
              </el-form-item>
            </el-col>
          </el-row> -->
          <el-row>
            <el-row>
              <el-col :span="10" :offset="1">
                <el-form-item label="课程" prop="courseId">
                  <select-course v-model="form.courseId" :clearable="true" :filterable="true" @change="changeCourse" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="10" :offset="1">
                <el-form-item label="课程名称" prop="name">
                  <el-input v-model.trim="form.name" placeholder="请输入课程名称" maxlength="64" show-word-limit clearable />
                </el-form-item>
              </el-col>
              <el-col :span="10" :offset="2">
                <el-form-item label="课程价格" prop="price">
                  <el-input v-model.trim="form.price" type="number" placeholder="请输入课程价格" clearable />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- <el-row style="text-align: left;">
              <el-col :span="10" :offset="1">
                <el-form-item label="缩略图" prop="thumbnail"><upload-img v-model="form.thumbnail" /></el-form-item>
              </el-col>
            </el-row>
            <el-row style="text-align: left;">
              <el-col :span="10" :offset="1">
                <el-form-item label="横幅" prop="banner"><upload-img v-model="form.banner" /></el-form-item>
              </el-col>
            </el-row> -->
            <!-- <el-row style="text-align: left;">
              <el-col :span="10" :offset="1">
                <el-form-item label="课程介绍" prop="introduceUrl"><upload-img v-model="form.introduceUrl" /></el-form-item>
              </el-col>
            </el-row> -->
          </el-row>

          <el-divider content-position="left">开课信息</el-divider>
          <el-row style="text-align: left;">
            <el-col :span="10" :offset="1">
              <el-form-item label="学年" prop="schoolYear" v-if=show>
                <select-school-year v-model="form.schoolYear" />
              </el-form-item>
              <el-form-item label="学期" prop="semester" v-if=show>
                <select-semester v-model="form.semester" />
              </el-form-item>
              <el-form-item label="学校" prop="schoolId">
                <select-school v-model="form.schoolId" :select-grade="selectGrade" @change="changeSchoolList" />
              </el-form-item>
              <el-form-item label="班级" prop="gradeName">
                <el-select v-model="form.gradeName" placeholder="请选择班级" style="width: 100%;" multiple @focus="selectGrade = true">
                  <el-option v-for="item in constants.GRADE_NAME_LIST" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <!-- <el-form-item label="群二维码" prop="wxGroupQRUrl">
                <upload-img v-model="form.wxGroupQRUrl" />
              </el-form-item> -->
            </el-col>

            <el-col :span="10" :offset="1">
              <el-form-item label="课程类型" prop="type">
                <el-select v-model="form.type" style="width: 100%;" placeholder="请选择课程类型">
                  <el-option v-for="item in constants.OPEN_COURSE_TYPE_LIST" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="开班人数" prop="openCourseNumber">
                <el-input v-model.trim="form.openCourseNumber" type="number" placeholder="请输入开班人数" clearable />
              </el-form-item>
              <el-form-item label="空闲人数" prop="freeCourseNumber">
                <el-input v-model.trim="form.freeCourseNumber" type="number" placeholder="请输入空闲人数" clearable />
              </el-form-item>
              <el-form-item label="每周上课" prop="cycle">
                <el-select v-model="form.cycle" style="width: 100%;" placeholder="请选择星期" clearable>
                  <el-option v-for="item in constants.WEEK_CYCLE_LIST" :key="item" :label="item" :value="item" />
                </el-select>
              </el-form-item>
              <el-form-item label="上课时间" prop="hours">
                <el-time-picker
                  v-model="hours"
                  is-range
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  placeholder="选择时间范围"
                  format="HH:mm"
                  value-format="HH:mm"
                  style="width: 100%"
                />
              </el-form-item>

              <el-form-item label="报名时间" prop="signUpTime">
                <el-date-picker
                  v-model="form.signUpTime"
                  type="datetimerange"
                  :picker-options="pickerOptions"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  align="right"
                  :default-time="['00:00:00', '23:59:59']"
                  value-format="yyyy-MM-dd HH:mm:ss"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="21" :offset="1">
              <el-form-item label="备注">
                <el-input v-model.trim="form.remarks" type="textarea" placeholder="请输入备注" rows="3" maxlength="255" show-word-limit clearable />
              </el-form-item>
            </el-col>
          </el-row>
        </el-row></el-form>

      <div slot="footer" class="dialog-footer">
        <el-divider />
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSave">确 定</el-button>
      </div>
    </el-dialog>
    <comment-item-drawer v-model="isShowCommentDrawer" @close="isShowCommentDrawer = false" />
    <order-item-drawer v-model="isShowOrderItemDrawer" :open-course="openCourse" @close="isShowOrderItemDrawer = false" />
  </el-row>
</template>

<script>
import fullCalendar2 from 'vue-fullcalendar'
import 'fullcalendar/dist/fullcalendar.css'
/* import UploadImg from '@/components/common/upload/upload-img' */
import { SelectSchool } from '@/components/school'
import { SelectOrgan } from '@/components/organ'
import { CourseType, SelectCourse } from '@/components/course'
import { SelectSchoolYear, SelectSemester } from '@/components/school-year-semester'
import CommentItemDrawer from './comment-item-drawer'
import OrderItemDrawer from './order-item-drawer'
import openCourseApi from '@/api/openCourseApi'

// todo 补一个详情页面效果
export default {
  name: '430OpenCourse',
  components: {
    'comment-item-drawer': CommentItemDrawer,
    /* 'upload-img': UploadImg, */
    'select-school': SelectSchool,
    'select-organ': SelectOrgan,
    'select-course': SelectCourse,
    'select-school-year': SelectSchoolYear,
    'select-semester': SelectSemester,
    'course-type': CourseType,
    'order-item-drawer': OrderItemDrawer,
    'full-calendar2': fullCalendar2
  },
  data() {
    const validateNumber = (rule, value, callback) => {
      if (!Number.isInteger(Number(value))) {
        callback(new Error('请输入正确的数字'))
      }
      if (rule.field === 'price' && (value === '' || value < 0)) {
        callback(new Error('请输入价格'))
      }
      if (rule.field === 'openCourseNumber' && (value === '' || value <= 0)) {
        callback(new Error('请输入开班人数'))
      }
      if (rule.field === 'freeCourseNumber' && (value === '' || value <= 0)) {
        callback(new Error('请输入空闲人数'))
      }
      callback()
    }
    return {
      config: {
        firstDay: 0,
        locale: 'zh-cn',
        defaultView: 'month',

        height: 'auto',
        header: {
          left: 'title',
          center: '',
          right: 'prev,today,next'
        },
        /* agenda 模式 */
        allDaySlot: false,
        editable: true,
        /* 设置按钮文字 */
        buttonText: {
          today: '今天'
        }
      },
      //
      show:true,
      searchForm: {
        schoolId: '', // 学校标识
        name: '', // 课程名称
        type: '430课程', // 课程类型
        schoolYear: '', // 学年
        semester: '', // 学期
        organIds: [],
        isDel: false,
        page: 1,
        size: 50
      },
      activeName: '1',
      total: 0,
      tableData: [],

      pickerOptions: {
        shortcuts: [{
          text: '未来一周',
          onClick(picker) {
            const start = new Date()
            const end = new Date()
            end.setTime(end.getTime() + 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '未来两周',
          onClick(picker) {
            const start = new Date()
            const end = new Date()
            end.setTime(end.getTime() + 3600 * 1000 * 24 * 14)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '未来三周',
          onClick(picker) {
            const start = new Date()
            const end = new Date()
            end.setTime(end.getTime() + 3600 * 1000 * 24 * 21)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      timetableData: [],
      t: true,
      gradeList: [],
      selectGrade: false,
      hours: ['16:05', '17:05'],
      dialogTitle: '',
      dialogVisible: false,
      form: {
        id: '', // 标识
        courseId: '', // 课程标识
        name: '', // 课程名称
        price: '', // 课程价格
        thumbnail: '1', // 缩略图
        banner: '1', // 横幅
        introduceUrl: '', // 课程介绍
        schoolYear: '', // 学年
        semester: '', // 学期
        schoolId: '', // 学校标识
        gradeName: [], // 班级
        type: '430课程', // 课程类型
        openCourseNumber: 30, // 开班人数
        freeCourseNumber: 30, // 空闲人数
        cycle: '', // 星期几
        hours: '', // 上课时间
        wxGroupQRUrl: '1', // 群二维码
        signUpTime: '', // 临时属性
        signUpStartTime: '', // 报名开始时间
        signUpEndTime: '', // 报名结束时间
        remarks: '', // 备注
        organId: ''
      },
      formRules: {
        courseId: [{ required: true, message: '请选择课程', trigger: 'blur' }],
        name: [{ required: true, message: '请输入课程名称', trigger: 'blur' }],
        price: [{ required: true, validator: validateNumber, trigger: 'blur' }],
       // banner: [{ required: true, message: '请上传横幅', trigger: 'blur' }],
        schoolYear: [{ required: true, message: '请选择学年', trigger: 'blur' }],
        semester: [{ required: true, message: '请选择学期', trigger: 'blur' }],
        schoolId: [{ required: true, message: '请选择学校', trigger: 'blur' }],
        gradeName: [{ required: true, message: '请选择班级', trigger: 'blur' }],
        type: [{ required: true, message: '请选择课程类型', trigger: 'blur' }],
        openCourseNumber: [{ required: true, validator: validateNumber, trigger: 'blur' }],
        freeCourseNumber: [{ required: true, validator: validateNumber, trigger: 'blur' }],
        cycle: [{ required: true, message: '请选择每周上课', trigger: 'blur' }],
        hours: [{ required: true, message: '请选择上课时间', trigger: 'blur' }],
        signUpTime: [{ required: true, message: '请选择报名时间', trigger: 'blur' }],
        /* organId: [{ required: true, message: '请选择机构', trigger: 'blur' }] */
      },

      openCourse: {},
      isShowCommentDrawer: false,
      isShowOrderItemDrawer: false
    }
  },
  mounted() {
    this.list()
    this.findTimetable()
  },
  methods: {
    findTimetable() {
      openCourseApi.timetable(this.searchForm).then(data => {
        this.timetableData = data
      })
    },
    handleAdd: function() {
      this.show = true
      let thisWeek = this.getDay(0)
      let nextTwoWeeks = this.getDay(14)
      thisWeek = thisWeek + ' 00:00:00'
      nextTwoWeeks = nextTwoWeeks + ' 23:59:59'

      /* 重置表单 */
      this.form['id'] = '' // 标识
      this.form['courseId'] = '' // 课程标识
      this.form['name'] = '' // 课程名称
      this.form['price'] = '' // 课程价格
      this.form['thumbnail'] = '1' // 缩略图
      this.form['banner'] = '1' // 横幅
      this.form['introduceUrl'] = '' // 课程介绍
      this.form['schoolYear'] = '' // 学年
      this.form['semester'] = '' // 学期
      this.form['schoolId'] = '' // 学校标识
      this.form['gradeName'] = [] // 班级
      this.form['type'] = '430课程' // 课程类型
      this.form['openCourseNumber'] = 30 // 开班人数
      this.form['freeCourseNumber'] = 30 // 空闲人数
      this.form['cycle'] = '' // 星期几
      this.form['hours'] = '' // 上课时间
      this.form['wxGroupQRUrl'] = '1' // 群二维码
      this.form['remarks'] = '' // 备注
      this.form['signUpTime'] = [thisWeek, nextTwoWeeks]
      this.form['organId'] = ''
      this.dialogTitle = '新增'
      this.dialogVisible = true

      this.gradeList = []
      this.selectGrade = false
    },
    handleEdit(index, row) {
      this.show = false
      /* 重置表单 */
      this.form['id'] = row.id // 标识
      this.form['courseId'] = row.courseId // 课程标识
      this.form['name'] = row.name // 课程名称
      this.form['price'] = row.price // 课程价格
      this.form['thumbnail'] = row.thumbnail // 缩略图
      this.form['banner'] = row.banner // 横幅
      this.form['introduceUrl'] = row.introduceUrl // 课程介绍
      this.form['schoolYear'] = row.schoolYear // 学年
      this.form['semester'] = row.semester // 学期
      this.form['schoolId'] = row.schoolId // 学校标识
      this.form['gradeName'] = row.gradeName.split(',') // 班级
      this.form['type'] = row.type // 课程类型
      this.form['openCourseNumber'] = row.openCourseNumber // 开班人数
      this.form['freeCourseNumber'] = row.freeCourseNumber // 空闲人数
      this.form['cycle'] = row.cycle // 星期几
      this.form['hours'] = row.hours // 上课时间
      this.form['signUpTime'] = [row.signUpStartTime, row.signUpEndTime] // 报名时间
      this.form['wxGroupQRUrl'] = row.wxGroupQRUrl // 群二维码
      this.form['remarks'] = row.remarks // 备注

      this.dialogTitle = '编辑'
      this.dialogVisible = true

      this.gradeList = []
      this.selectGrade = false
      // 时间拆解
      this.hours = row.hours.replace(/\s*/g, '').split('~')
    
    },
    handleIsDel(index, row) {
      openCourseApi.handleIsDel(row.id).then(data => {
        this.list()
      })
    },
    handleSave() {
      /* 处理开课时间字段 */
      let timeString = ''
      this.hours.forEach((item, index) => {
        timeString += item
        if (index === 0) {
          timeString += ' ~ '
        }
      })
      this.form['hours'] = timeString
      this.$refs['form'].validate((valid) => {
        if (!valid) {
          return
        }

        this.form['signUpStartTime'] = this.form['signUpTime'][0] // 报名开始时间
        this.form['signUpEndTime'] = this.form['signUpTime'][1] // 报名结束时间
        this.form['gradeName'] = this.form['gradeName'].join(',') // 拼接班级数组

        openCourseApi.saveOrUpdate(this.form).then(data => {
          this.list()

          this.dialogVisible = false
          this.$refs['form'].resetFields()
        })
      })
    },
    searchChangeSchool(o) {
      if (o) {
        this.searchForm['schoolId'] = o.id
      } else {
        this.searchForm['schoolId'] = ''
      }
      this.list()
    },
    eventClick(event) {
      console.log(event)
    },
    dayClick(day, jsEvent) {
      console.log('dayClick', day, jsEvent)
    },
    changeCourse(course) {
      this.form['courseId'] = course.id
      this.form['name'] = course.name // 课程名称
      this.form['price'] = course.price // 课程价格
      this.form['thumbnail'] = course.thumbnail // 缩略图
      this.form['banner'] = course.banner // 横幅
      this.form['introduceUrl'] = course.introduceUrl // 课程介绍
      this.form['remarks'] = course.remarks // 备注
    },
    changeSchoolList(school) {
      this.gradeList = []
      const arr = school.gradeYear.split(',')
      arr.map(item => {
        this.gradeList = this.gradeList.concat(this.constants.GRADE_NAME_LIST2[item - 1])
      })
    },
    list() {
      if (this.activeName === '1') {
        this.tableData = []
        openCourseApi.page(this.searchForm).then(data => {
          this.total = data.total
          this.tableData = data.data
        })
      } else {
        this.findTimetable()
      }
    },
    changeSizeChange(val) {
      this.searchForm.size = val
      this.list()
    },
    changeCurrentChange(val) {
      this.searchForm.page = val
      this.list()
    },
    openOrderItemView(row) {
      this.isShowOrderItemDrawer = true
      this.openCourse = row
    },
    getDay(day) {
      var today = new Date()
      var tar = today.getTime() + 1000 * 60 * 60 * 24 * day
      today.setTime(tar)
      var tYear = today.getFullYear()
      var tMonth = today.getMonth()
      var tDate = today.getDate()
      tMonth = this.doHandleMonth(tMonth + 1)
      tDate = this.doHandleMonth(tDate)
      return tYear + '-' + tMonth + '-' + tDate
    },
    doHandleMonth(month) {
      var m = month
      if (month.toString().length === 1) {
        m = '0' + month
      }
      return m
    }
  }
}
</script>

<style scoped>
</style>
