<template>
  <div>
    <div class="newBand"
         v-permission="'vipGroupManage/addVipGroupStudents'"
         @click="addStudentList">新增学员</div>
    <div class="tableWrap">
      <el-table :data='tableList'
                :header-cell-style="{background:'#EDEEF0',color:'#444'}">
        <el-table-column label="学员姓名"
                         prop="userName"
                         align="center"
                         width="180">
        </el-table-column>
        <el-table-column label="手机号"
                         align="center"
                         prop="phone"
                         width="180">
        </el-table-column>
        <el-table-column prop="studentStatus"
                         align="center"
                         label="学员状态">
          <template slot-scope="scope">
            <div>
              {{ scope.row.studentStatus | studentStatus }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="courseSalary"
                         align="center"
                         label="课程余额"></el-table-column>
        <el-table-column prop="applyDate"
                         align="center"
                         label="报名时间">
          <template slot-scope="scope">
            <div>
              {{scope.row.applyDate |formatTimer }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="refundDate"
                         align="center"
                         label="退课时间">
          <template slot-scope="scope">
            <div>
              {{scope.row.refundDate |formatTimer }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作"
                         align="center">
          <template slot-scope="scope">
            <div>
              <!-- <el-popover placement="top"
                          width="160"
                          trigger="click"
                          :ref="scope.$index">
                <p>请输入退费金额</p>
                <el-input style="margin:10px 0;"
                          type="number"
                          v-model.trim="scope.row.fee"></el-input>
                <div style="text-align: right; margin-top: 20px">
                  <el-button size="mini"
                             type="text"
                             @click="scope._self.$refs[scope.$index].doClose()">取消</el-button>
                  <el-button type="primary"
                             size="mini"
                             @click="leaveSchool(scope)">确定</el-button>
                </div>
                <el-button type="text"
                           slot="reference"
                           @click="lookFee(scope)">退学</el-button>
              </el-popover> -->
              <el-button type="text"
                         v-if="scope.row.studentStatus == 0"
                         v-permission="'vipGroupManage/applyRefundForStudent'"
                         @click="lookFee(scope)">退学</el-button>
              <!--   v-permission="'vipGroupManage/applyRefundForStudent'" -->
              <el-button type="text"
                         v-if="scope.row.studentStatus == 0"
                         @click="stopCourse(scope)">休学</el-button>
              <el-button type="text"
                         v-if="scope.row.studentStatus == 3"
                         @click="recoveryCourse(scope)">恢复</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog title="学员列表"
               width="70%"
               :visible.sync="maskVisible">
      <el-form :model="maskForm"
               :inline="true">
        <el-form-item>
          <el-input placeholder="请输入学生姓名或手机号"
                    @keyup.enter.native='search'
                    v-model.trim='maskForm.search'></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="danger"
                     @click="search">搜索</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"
                     @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="maskStudentList"
                :header-cell-style="{background:'#EDEEF0',color:'#444'}">
        <el-table-column label=""
                         width="55">
          <template slot-scope="scope">
            <el-radio v-model.trim="activeStudent"
                      :label="scope.row.id"
                      @change.native="getTemplateRow(scope.$index,scope.row)">&nbsp</el-radio>
          </template>
        </el-table-column>
        <el-table-column prop="userName"
                         align="center"
                         label="学生姓名"
                         width="150"></el-table-column>
        <el-table-column prop="phone"
                         align="center"
                         label="手机号"
                         width="200"></el-table-column>
        <el-table-column prop="courseSalary"
                         label="课程余额"></el-table-column>

      </el-table>
      <pagination :total="rules.total"
                  :page.sync="rules.page"
                  :limit.sync="rules.limit"
                  :page-sizes="rules.page_size"
                  @pagination="getList" />
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="maskVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="addStudent">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="学员复学"
               width="800px"
               :visible.sync="adjustmentVisible">
      <el-form :model='adjustmentForm'
               label-position="right"
               label-width="120px"
               ref='adjustmentForm'
               :rules="adjustmentRules"
               :inline="true">
        <el-form-item label="剩余课时">
          <el-input disabled
                    v-model.trim="adjustmentForm.count"></el-input>
        </el-form-item>
        <el-form-item label="任课老师"
                      prop="teacher">
          <el-select v-model.trim="adjustmentForm.teacher">
            <el-option v-for="(item,index) in teacherList"
                       :key="index"
                       :label="item.realName"
                       :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <!-- <br> -->
        <!-- <el-form-item label="单课费用"
                      prop="fee">
          <el-input v-model.trim="adjustmentForm.fee"></el-input>
        </el-form-item> -->
        <!-- <el-form-item label="课程类型"
                      prop="courseType">
          <el-select clearable
                     v-model.trim="adjustmentForm.courseType">
            <el-option label="线上课"
                       value="ONLINE"></el-option>
            <el-option label="线下课"
                       value="OFFLINE"></el-option>
          </el-select>
        </el-form-item> -->
        <br>
        <el-form-item label="排课起始时间"
                      prop="courseTime">
          <el-date-picker v-model.trim="adjustmentForm.courseTime"
                          :picker-options="pickerOptions"
                          style="width:200px!important;"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择日期">
          </el-date-picker>
          <el-checkbox style='margin-left:10px;'
                       v-model.trim="adjustmentForm.checked">是否跳过节假日</el-checkbox>
        </el-form-item>
      </el-form>
      <div class="WeekWrap ">
        <h3 style="margin-bottom:20px;">循环次数 <el-button type="text"
                     style='margin-left:10px;'
                     @click="addWeek">添加</el-button>
        </h3>
        <div class="countWrap"
             style="margin-bottom:10px;">
          <div class="countItem"
               style="margin-bottom:20px;"
               v-for="(item,index) in weekList"
               :key="index">
            <span>循环周期: </span>
            <el-select v-model.trim="item.dayOfWeek"
                       filterable
                       clearable>
              <el-option v-for="(item,index) in weekDateList"
                         :key='index'
                         :label="item.label"
                         :value="item.value"></el-option>
            </el-select>
            <span style="margin-left:10px;">开始时间</span>
            <el-time-select style="margin-left:10px;"
                            placeholder=""
                            v-model.trim="item.startClassTime"
                            :picker-options="{
                               start: '04:30',
                               step: '00:05',
                               end: '23:55'
            }">
            </el-time-select>
            <el-button style="margin-left:10px;"
                       type="danger"
                       @click="removeWeek(item)"
                       icon="el-icon-delete"
                       circle></el-button>
          </div>
        </div>
      </div>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="adjustmentVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="submieRecover">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import pagination from '@/components/Pagination/index'
import { findVipGroupStudents, leaveSchool, getStudentSurplusCourseFee, getHaveCourseBalanceStudents, addVipGroupStudents, vipPauseForStudent, getStudentPauseInfo, recoverForStudent, findTeacherWithVipGroupOrganAndSubject } from '@/api/vipSeting'
export default {
  components: { pagination },
  data () {
    return {
      adjustmentVisible: false,
      tableList: [],
      id: '',
      maskStudentList: [],
      maskVisible: false,
      rules: {
        // 分页规则
        limit: 10, // 限制显示条数
        page: 1, // 当前页
        total: 0, // 总条数
        page_size: [10, 20, 40, 50] // 选择限制显示条数
      },
      activeStudent: '',
      maskForm: {
        search: ''
      },
      adjustmentForm: {
        count: '',
        courseTime: '',
        checked: false,
        addCount: '',
        courseType: '',
        fee: '',
        teacher: ''
      },
      adjustmentRules: {
        courseTime: [{ required: true, message: '请选择开始时间' }],
        addCount: [{ required: true, message: '请输入加课次数' }],
        courseType: [{ required: true, message: '请选择课程类型' }],
        fee: [{ required: true, message: '请输入费用' }],
        teacher: [{ required: true, message: '请选择老师' }]
      },
      weekDateList: [
        { value: '1', label: '星期一' },
        { value: '2', label: '星期二' },
        { value: '3', label: '星期三' },
        { value: '4', label: '星期四' },
        { value: '5', label: '星期五' },
        { value: '6', label: '星期六' },
        { value: '7', label: '星期日' },
      ],
      weekList: [{
        dayOfWeek: '',
        startTime: '',
        endTime: '',
        moid: new Date().getTime()
      }],
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() + 86400000 <= new Date().getTime()
        }
      },
      teacherList: []
    }
  },
  mounted () {
    this.__init()
  }, 
  activated() {
    this.__init()
  },
  methods: {
    __init() {
      let id = this.$route.query.id;
      this.id = id;
      this.getStudents()
      findTeacherWithVipGroupOrganAndSubject({ vipGroupId: this.id }).then(res => {
        if (res.code == 200) {
          this.teacherList = res.data;
        }
      })
    },
    search () {
      this.rules.page = 1;
      this.getList()
    },
    reset () {
      this.rules.page = 1;
      this.maskForm.search = null;
      this.activeStudent = '';
      this.getList();
    },
    getStudents () {
      findVipGroupStudents({ vipGroupId: this.id }).then(res => {
        if (res.code == 200) {
          this.tableList = res.data.rows;
          for (let i in this.tableList) {
            this.tableList[i].fee = 0;
            this.tableList[i].visible = false;
          }
        }
      })
    },
    // 删除循环周
    removeWeek (item) {
      for (let i in this.weekList) {
        if (this.weekList[i].id == item.id) {
          this.weekList.splice(i, 1)
        }
      }
    },
    leaveSchool (scope) {
      let studentId = scope.row.id;
      let vipGroupId = this.id;
      let amount = scope.row.fee;
      leaveSchool({ studentId, vipGroupId, amount }).then(res => {
        if (res.code == 200) {
          this.$message.success('退学成功')
          this.getStudents();

        }
      })

    },
    lookFee (scope) {
      this.$confirm(`确定是否退学?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let id = scope.row.id;
        getStudentSurplusCourseFee({ studentId: id, vipGroupId: this.id }).then(res => {
          if (res.code == 200) {
            // scope.row.fee =
            this.$prompt('请输入退课金额', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              inputValue: res.data.suplusCourseFee
            }).then(({ value }) => {
              scope.row.fee = value;
              this.leaveSchool(scope);
            }).catch(res => {

            })
          }
        })
      }).catch(() => { })

    },
    addStudentList () {
      // 发请求 搜索学生
      this.getList();
    },
    getList () {
      let search = this.maskForm.search || null;
      getHaveCourseBalanceStudents({ organId: null, page: this.rules.page, rows: this.rules.limit, search }).then(res => {
        if (res.code == 200) {
          this.rules.total = res.data.total;
          this.maskStudentList = res.data.rows;
          this.maskVisible = true;
        }
      })
    },
    getTemplateRow (index, row) {
      this.activeStudent = row.id;
    },
    addStudent () {
      if (!this.activeStudent) {
        this.$message.error('请选择一名学生');
        return
      }
      addVipGroupStudents({ vipGroupId: this.id, studentIds: this.activeStudent }).then(res => {
        if (res.code == 200) {
          this.$message.success('添加成功')
          this.getStudents()
        }
      })
    },
    stopCourse (scope) {
      this.$confirm('是否休学?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发请求 申请休学
        vipPauseForStudent({ vipGroupId: this.id, studentId: scope.row.id }).then(res => {
          if (res.code == 200) {
            this.$message.success('休学成功')
            this.getStudents()
          }
        })
      }).catch(() => {
      });
    },
    recoveryCourse (scope) {
      getStudentPauseInfo({ studentId: scope.row.id, vipGroupId: this.id }).then(res => {
        if (res.code == 200) {

          if (res.data.isPause == 0) {
            // vip状态没暂停 不需要排课
            // 课程编号  学生编号
            this.$confirm('将按照当前剩余课时安排上课', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              // 发请求 恢复上课
              recoverForStudent({ vipGroupId: this.id, userId: scope.row.id }).then(res => {
                if (res.code == 200) {
                  this.adjustmentVisible = false;
                  this.getStudents()
                }
              })

            }).catch(() => {
            });

          } else {
            this.activeStudent = res.data.studentId
            this.adjustmentVisible = true;
            this.adjustmentForm.teacher = res.data.teacherId;
            this.adjustmentForm.count = `${res.data.totalCourseTimes}+${res.data.giveCourseTimes}`
          }

        }
      })


      // this.$confirm('是否休学?', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).then(() => {
      //   // 发请求 申请休学
      //   vipPauseForStudent({ vipGroupId: this.id, studentId: scope.row.id }).then(res => {
      //     if (res.code == 200) {
      //       this.$message.success('休学成功')
      //       this.getList()
      //     }
      //   })
      // }).catch(() => {
      // });
    },
    addWeek () {
      // 添加循环周期
      this.weekList.push({
        dayOfWeek: '',
        startClassTime: '',
        endClassTime: '',
        id: new Date()
      })
    },
    submieRecover () {
      if(this.weekList.length <= 0) {
        this.$message.error('排课循环次数不能为空')
        return
      }
      this.$refs['adjustmentForm'].validate(res => {
        if (res) {
          // 发请求
          let obj = {}
          obj.courseCreateStartTime = this.adjustmentForm.courseTime;
          obj.skipHoliday = this.adjustmentForm.checked;
          obj.teacherId = this.adjustmentForm.teacher;
          obj.userId = this.activeStudent;
          obj.courseTimes = [];
          obj.courseTimes = this.weekList
          obj.vipGroupId = this.id
          recoverForStudent(obj).then(res => {
            if (res.code == 200) {
              this.adjustmentVisible = false;
              this.getStudents()
            }
          })
        } else {
          this.$message.error('请填写必要参数')
        }
      })
      this.activeStudent;
    }
  },
}
</script>
<style lang="scss" scoped>
</style>