<template>
  <div class="context">
    <div class="panel">
      <h5>课程管理</h5>
      <div class="likeTab">
        <el-button type="primary" @click="goType('classManage')" size="mini">当前课程</el-button>
        <el-button @click="goType('classHistory')" size="mini">历史记录</el-button>
      </div>
      <div class="panel-body">
        <div class="panel_control">
          <el-row :gutter="20">
            <el-col :span="7">
              <el-date-picker v-model="panel.timeScope" type="daterange" range-separator="至"
                              start-placeholder="开始日期" end-placeholder="结束日期">
              </el-date-picker>
            </el-col>
            <el-col :span="4">
              <el-button size="" type="primary" @click="query" :disabled="searchBtnStatus" plain>查询
              </el-button>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>

    <div class="table">
      <el-table :data="tableData" border is-horizontal-resize :default-sort="{prop: 'date', order: 'descending'}"
                element-loading-background="rgba(0, 0, 0, 0.8)" class="" @selection-change="handleSelectionChange">
        <el-table-column label="序号" type="index" width="50" align="center" fixed>
          <template scope="scope">
            <span>{{ (start) + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="begin_time" label="上课时间" width="160" :formatter="filterFmtDate" fixed>
        </el-table-column>
        <el-table-column prop="class_name" label="课程" sortable width="120" fixed>
          <template slot-scope="scope">
                        <span class="lessonSpan"
                              :style="{background:scope.row.ClassColor}">{{ scope.row.class_name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="course_type" label="课程类型" width="110" sortable>
          <template slot-scope="scope">
            <span v-if="scope.row.course_type == 1">室内课</span>
            <span v-if="scope.row.course_type == 2">户外课</span>
            <span v-if="scope.row.course_type == 3">线上课</span>
            <span v-if="scope.row.course_type == 4">混合课</span>
          </template>
        </el-table-column>
        <el-table-column prop="class_type" label="上课方式" width="110" sortable>
          <template slot-scope="scope">
            <span v-if="scope.row.class_type == 1">团课</span>
            <span v-if="scope.row.class_type == 3">私教</span>
            <span v-if="scope.row.class_type == 2 && scope.row.PkNum == 2">两队PK</span>
            <span v-if="scope.row.class_type == 2 && scope.row.PkNum == 3">三队PK</span>
          </template>
        </el-table-column>
        <el-table-column prop="sv_name" label="区域" width="110" sortable/>
        <el-table-column prop="consume_hour" label="消耗课时" width="110" sortable/>
        <el-table-column prop="order_num" label="实际预约" width="110" sortable/>
        <el-table-column prop="wx_order" label="预约状态" width="110" sortable>
          <template slot-scope="scope">
            <span v-if="scope.row.wx_order == 1" style="color: yellowgreen">可约</span>
            <span v-if="scope.row.wx_order == 0" style="color: red">不可约</span>
          </template>
        </el-table-column>
        <el-table-column prop="finish_class" label="当前状态" width="110" sortable>
          <template slot-scope="scope">
            <span v-if="scope.row.finish_class == 0" style="color: red">未上课</span>
            <span v-if="scope.row.finish_class == 1">已下课</span>
            <span v-if="scope.row.finish_class == 2" style="color: yellowgreen">已上课</span>
            <span v-if="scope.row.finish_class == 3">准备上课</span>
            <span v-if="scope.row.finish_class == 4">已完成</span>
          </template>
        </el-table-column>
        <el-table-column prop="Status" label="操作">
          <template slot-scope="scope">
            <el-button type="primary" round size="mini" v-if="scope.row.finish_class == 0"
                       @click="showDialogClassOn(scope.row)"> 上课
            </el-button>
            <el-button type="primary" round size="mini"
                       v-if="scope.row.finish_class == 3 || scope.row.finish_class == 2"
                       @click="classManage(scope.row)">
              管理
            </el-button>
            <!--修改区域 todo-->
            <el-button type="primary" round plain size="mini" v-if="scope.row.finish_class == 3"
                       @click="classEdit(scope.row)">
              编辑
            </el-button>
            <!--已完成才能看详情-->
            <el-button type="primary" round plain size="mini"
                       v-if="scope.row.finish_class == 1 || scope.row.finish_class == 4"
                       @click="classDetail(scope.row)">
              详情
            </el-button>

          </template>
        </el-table-column>
      </el-table>
      <br>
      <el-pagination background :total="pagination.total" :page-size="pagination.pageItem"
                     @current-change="pageChange" :current-page.sync="cur_page"></el-pagination>
    </div>
    <el-dialog :title="dialogTitle" :visible.sync="dialogClassPrepareVisible" width="650px">
      <div class="dialogContent">
        <h5 class="classNames">{{ className }}</h5>
        <div class="">
          <el-form ref="form" :model="form" label-width="160px">
            <!--选教练，非必选-->
            <el-form-item label="上课教练">
              <el-select v-model="coachValue" filterable placeholder="请选择">
                <el-option v-for="item in form.coachData" :key="item.key" :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <!--课程类型-->
            <el-form-item label="课程类型" :required="true">
              <el-select v-model="form.courseType" filterable placeholder="请选择">
                <el-option v-for="item in form.courseTypeOptions" :key="item.value" :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <!--是否是心率课-->
            <el-form-item align="left">
              <span style="margin-left: -60px">
                心率课
              <el-switch
                  style="margin-left: 30px"
                  v-model="form.IsHr"
                  active-color="#13ce66"
                  inactive-color="#ff4949">
              </el-switch>
              </span>
              <span style="margin-left: 50px">
                评分课
              <el-switch
                  style="margin-left: 30px"
                  v-model="form.IsScore"
                  active-color="#13ce66"
                  inactive-color="#ff4949">
              </el-switch>
              </span>
            </el-form-item>

            <!--选择区域-->
            <el-form-item label="区域" :required="true">
              <el-select v-model="form.svId" filterable placeholder="请选择" @change="changeLocationValue">
                <el-option v-for="item in form.svList" :key="item.SvId" :label="item.Name"
                           :value="item.SvId">
                </el-option>
              </el-select>
            </el-form-item>
            <!--显示设备-->
            <el-form-item label="显示设备">
              <el-checkbox-group v-model="form.equipList">
                <el-checkbox label="复选框 A"></el-checkbox>
                <el-checkbox label="复选框 B"></el-checkbox>
                <el-checkbox label="复选框 C"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <!--上课方式-->
            <el-form-item label="上课方式" :required="true">
              <el-select v-model="form.classType" filterable placeholder="请选择">
                <el-option v-for="item in form.classTypeOptions" :key="item.value" :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <!--分队方式-->
            <el-form-item label="分队方式" v-if="form.classLabel == 2">
              <el-select v-model="form.pkNum" filterable placeholder="请选择">
                <el-option v-for="item in form.PKTypeOptions" :key="item.value" :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>

          </el-form>
        </div>
      </div>
      <div class="dialogFooter">
        <el-button type="primary" size="small" v-if="form.btnType == 0" :disabled="PrepareBtnStatus"
                   @click="getClassStartPrepare()">确定
        </el-button>
        <el-button type="primary" size="small" v-if="form.btnType == 1" @click="getClassStartPrepareForEdit()">
          确定
        </el-button>
        <el-button size="small" @click="dialogClassPrepareVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Global from '../../Global.js'
import {
  ClassOverPrepare,
  QueryShopVenue,
  ClassStartPrepare,
  DispPlanInfoEdit,
  ShopManagerListQuery,
} from "../../api/getApiRes";

import {
  StandardRequest
} from "@/grpc/base_pb";

let qs = require('qs');
export default {
  data() {
    return {
      dialogClassPrepareVisible: false,
      searchBtnStatus: false,
      PrepareBtnStatus: false,
      dialogTitle: '上课准备',
      coachValue: [],
      className: '',
      current: getNowDate(),
      dialogValue: [],
      start: 0,
      draw: 1,
      cur_page: 1,
      // panel 配置项目
      panel: {
        draw: 1,
        start: 0,
        recordsTotal: 0,
        tableData: [],
        allTableData: [],
        limit: '10',
        multipleSort: false,
        loading: false,
        fileList: [],
        multipleSelection: [],
        timeScope: globalBt2(0),
      },
      multipleSelection: [],
      pagination: {
        pageItem: 10,
        pagOptions: pageOptions(),
        total: 100,
        pageIndex: 1,
      },
      form: {
        svId: '',
        StdId: '',
        IsHr: 1,
        IsScore: 1,
        svName: '',
        equipList: ['选中且禁用', '复选框 A'],
        classType: 1,//课程类型
        courseType: 1,//课程标签
        coach: '',
        coachOptions: [],
        pkNum: 2,
        btnType: 0,//0新建，1编辑
        svList: [],//区域列表
        coachData: [],//穿梭已选
        courseTypeOptions: [
          {value: 1, label: '室内课'},
          {value: 2, label: '户外课'},
          {value: 3, label: '线上课'},
          {value: 4, label: '混合课'}
        ],
        classTypeOptions: [
          {value: 1, label: '团课'},
          {value: 2, label: '竞技PK'},
          {value: 3, label: '私教课'}
        ],
        PKTypeOptions: [
          {value: 2, label: '2队PK'},
          {value: 3, label: '3队PK'}
        ],
      },
      tableData: []
    }
  },
  mounted() {
    this.getTableQuery();
  },
  methods: {
    goType(url) {
      this.$router.push({path: '/' + url});
    },
    // 更改上课区域
    classEdit(row) {
      this.dialogClassPrepareVisible = true;
      this.form.btnType = 1;//0新建，1编辑
      // 读取本行信息
      this.className = row.class_name + ' ' + row.begin_str + ' - ' + row.end_str;
      this.form.StdId = row.std_id;
      this.getQueryShopVenue();
      this.form.svId = row.sv_id;
      this.form.classType = row.class_type;
      this.form.courseType = row.course_type;
      this.form.pkNum = row.pk_num;
    },
    // 准备上课
    getClassStartPrepare() {
      let that = this;
      if (!that.form.svId) {
        that.$message.error('上课区域不能为空');
        return false
      }
      that.PrepareBtnStatus = true;
      // 不是竞技pk的时候为0
      let uppkNum = that.form.classType == 2 ? that.form.pkNum : 0;
      let tid = that.coachValue.toString();
      let param = {
        token: localStorage.token,
        stdId: that.form.StdId,
        svId: that.form.svId,
        svName: that.form.svName,
        classType: that.form.classType,
        pkNum: uppkNum,
        tid: tid,//教练id
      };
      that.searchBtnStatus = true;
      let totalTime = 2;
      let clock = window.setInterval(() => {
        totalTime--;
        if (totalTime < 0) {
          totalTime = 2;
          that.searchBtnStatus = false;
        }
      }, 1000);
      let postdata = qs.stringify(param);
      ClassStartPrepare(postdata).then(res => {
        that.PrepareBtnStatus = false;
        let json = res;
        if (json.Code == 0) {
          this.$router.push({
            path: '/classEdit',
            query: {
              StdId: that.form.StdId,
              ClassName: that.form.ClassName,
              BeginStr: that.form.BeginStr,
              EndStr: that.form.EndStr,
              FinishClass: 3,
              ClassType: that.form.classType,
              PkNum: uppkNum,
            }
          });
          that.dialogClassPrepareVisible = false;
          this.getTableQuery();

        } else {
          that.$message.error(json.Memo + ' 错误码：' + json.Code);
        }
      })
    },
    // 编辑
    getClassStartPrepareForEdit() {
      let that = this;
      if (!that.form.svId) {
        that.$message.error('上课区域不能为空');
        return false
      }
      // 不是竞技pk的时候为0
      let uppkNum = that.form.classType == 2 ? that.form.pkNum : 0;

      let param = {
        token: localStorage.token,
        stdId: that.form.StdId,
        svId: that.form.svId,
        svName: that.form.svName,
        classType: that.form.classType,
        pkNum: uppkNum,
      };
      let postdata = qs.stringify(param);
      DispPlanInfoEdit(postdata).then(res => {
        let json = res;
        if (json.Code == 0) {
          // NewId: 0
          that.dialogClassPrepareVisible = false;
          this.getTableQuery();
        } else {
          that.$message.error(json.Memo + ' 错误码：' + json.Code);
        }
      })
    },
    classDetail(row) {
      this.$router.push({
        path: '/classInfoDetail', query: {
          StdId: row.std_id,
          ClassName: row.class_name,
          BeginStr: row.begin_str,
          EndStr: row.end_str,
        }
      });
    },
    classManage(row) {
      this.$router.push({
        path: '/classEdit', query: {
          StdId: row.std_id,
          ClassName: row.class_name,
          BeginStr: row.begin_str,
          EndStr: row.end_str,
          FinishClass: row.finish_class,
          ClassType: row.class_type,
          PkNum: row.pk_num,
        }
      });
    },
    // 关课
    closeLesson(row) {
      that.$message.error('功能未上线，请耐心等候');
      return false;
      let that = this;
      let param = {
        token: localStorage.token,
        hrId: row.HrId,
        status: 9,//
      };
      let postdata = qs.stringify(param);
      this.$confirm('此操作将永久关闭当前课程, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        HrSensorsStatusEdit(postdata).then(res => {
          let json = res;
          if (json.Code == 0) {
            that.$message({
              showClose: true,
              message: '选中的课程已关闭！',
              type: 'success'
            });
            // 重载列表
            that.getTableQuery();
          } else {
            that.$message.error(json.Memo + ' 错误码：' + json.Code);
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消关课'
        });
      });
    },
    // 获取select的label
    changeLocationValue(val) {
      //locations是v-for里面的也是datas里面的值
      let obj = {};
      obj = this.form.svList.find((item) => {
        return item.SvId === val;
      });
      this.form.svName = obj.Name;
    },
    // 获取区域列表
    getQueryShopVenue() {
      let that = this;
      let param = {
        key: localStorage.ServiceKey,
        shopId: localStorage.ServiceId,
      };
      if (!localStorage.ServiceKey) {
        that.$message.error('还未与心率系统对接，请联系管理员');
        return false
      }
      let postdata = qs.stringify(param);
      QueryShopVenue(postdata).then(res => {
        let json = res;
        if (json.Code == 0) {
          that.form.svList = json.Rs;
        } else {
          that.$message.error(json.Memo + ' 错误码：' + json.Code);
        }
      })
    },
    vipSelect(stdId) {
      let that = this;
      // 筛选相同的stdid的classId
      that.form.stdList.map(function (item) {
        if (item.value == stdId) {
          let param = {
            token: localStorage.token,
            // classId: item.classId
          };
          let postdata = qs.stringify(param);
          // VipUserListQuery
          VipUserSimpleQuery(postdata).then(res => {
            let json = res;
            if (json.Code == 0) {
              that.form.userId = '';
              that.form.userList = turnResToOptionBySimViper(json.Rs);
            } else {
              that.$message.error(json.Memo + ' 错误码：' + json.Code);
            }
          })
        }
      })
    },
    //上课按钮弹出框
    showDialogClassOn(row) {
      this.dialogClassPrepareVisible = true;
      this.form.btnType = 0;//0新建，1编辑编辑
      // clear
      this.form.svList = "";
      this.form.StdId = row.std_id;
      this.form.ClassName = row.class_name;
      this.form.BeginStr = row.begin_str;
      this.form.EndStr = row.end_str;
      this.form.FinishClass = row.finish_class;
      this.form.ClassType = row.class_type;
      this.form.courseType = row.course_type;
      this.form.PkNum = row.pk_num;
      this.className = row.class_name + ' ' + row.begin_str + ' - ' + row.end_str;
      this.form.StdId = row.std_id;
      this.getCoachOption();
      this.getQueryShopVenue();
    },
    // 获取教练选项
    getCoachOption() {
      let that = this;
      let param = {
        token: localStorage.token,
        name: this.panel.name,//
        phone: this.panel.phone,//
        shopId: localStorage.ShopId,//
        adminType: 4,//
        start: 1,//
        tableMax: 299,//
      };
      let postdata = qs.stringify(param);
      ShopManagerListQuery(postdata).then(res => {
        let json = res;
        if (json.Code == 0) {
          that.form.coachData = turnResToOptionByUsers(json.Rs);
        } else {
          that.$message.error(json.Memo + ' 错误码：' + json.Code);
        }
      })
    },
    // 检测当前课是否处于可改变状态
    // 固定下当前已预约人数列表
    checkClassOverPrepare(row) {
      let that = this;
      let param = {
        token: localStorage.token,
        stdId: row.std_id,
      };
      let postdata = qs.stringify(param);
      ClassOverPrepare(postdata).then(res => {
        let json = res;
        if (json.Code == 0) {
          that.goFinish(row);
        } else {
          that.$message.error(json.Memo + ' 错误码：' + json.Code);
        }
      })
    },
    goFinish(row) {
      this.$router.push({
        path: '/classFinishDetail', query: {
          id: row.std_id,
          classId: row.ClassId,
          ClassName: row.class_name,
          BeginTime: row.begin_time,
        }
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 查询按钮
    query() {
      let that = this;
      that.start = 0;
      that.cur_page = 1;
      that.searchBtnStatus = true;
      let totalTime = 2;
      let clock = window.setInterval(() => {
        totalTime--;
        if (totalTime < 0) {
          totalTime = 2;
          that.searchBtnStatus = false;
        }
      }, 1000);
      this.getTableQuery();

      this.$message.success('查询完毕');
    },
    // 页面数据查询
    getTableQuery() {
      let that = this;
      that.loading = true;

      const jsonStr = {
        shopId: localStorage.shopId,
        bt: nonTfmtDatetoLength(that.panel.timeScope[0], 10) + " 00:00:00",
        et: nonTfmtDatetoLength(that.panel.timeScope[1], 10) + " 23:59:59",
        fcStatus: 1,// 0:历史记录(对应finishClass 10,4组合 ) 1:上课中
        courseType: -99,//-99是全部 1:室内课 2:户外课 3:线上课 4:混合课
        start: that.start,
        tableMax: that.pagination.pageItem
      };
      let paraRequest = new StandardRequest();
      paraRequest.setShopid(localStorage.shopId);
      paraRequest.setJsonstr(JSON.stringify(jsonStr));
      paraRequest.setSign(getSignStr(jsonStr));
      console.log(paraRequest);
      console.log(localStorage.token);
      that.client.courseDetailQuery(paraRequest, {"Token": localStorage.token}, (err, StandardReply) => {
        if (err == null) {
          console.log(StandardReply.getJsonrst());
          let res = JSON.parse(StandardReply);
          if (res.code === 0) {
            that.loading = false;
            if (res.rs) {
              that.allTableData = res.rs;
              that.recordsTotal = res.rs.length;
            } else {
              that.allTableData = [];
              that.recordsTotal = 0;
            }
            // 设置分页数据
            that.setPagination();
          } else {
            that.$message.error(res.memo + ',错误代码：' + res.code);
          }
        } else {
          let res = err;
          that.$message.error(res.message + ',错误代码：' + res.code);
          console.log(res);
        }
      });
    },
    // 设置分页数据
    setPagination() {
      // 分页属性
      let that = this;
      that.pagination.total = that.recordsTotal;

      // 默认分页
      that.tableData = that.allTableData.filter((item, index) => {
        return index < that.pagination.pageItem;
      });
    },
    // 每页显示数量
    handleSizeChange() {
      let that = this;
      that.tableData = that.allTableData.filter((item, index) => {
        return index < that.pagination.pageItem;
      });
      that.draw = that.pagination.pageItem;
      // that.getTableQuery();
    },
    // 翻页
    pageChange(pageIndex) {
      let that = this;
      // 获取当前页
      let index = that.pagination.pageItem * (pageIndex - 1);
      // 数据总数
      let nums = that.pagination.pageItem * pageIndex;
      // 容器
      let tables = [];
      for (var i = index; i < nums; i++) {
        if (that.allTableData[i]) {
          tables.push(that.allTableData[i])
        }
        this.tableData = tables;
      }
      that.start = index * that.draw;
      // that.getTableQuery();
    },
    // 过滤时间
    filterFmtDate(value, row, column) {
      let that = this;
      return nonTfmtDate(column, 11);
    },
  },
  watch: {
    $route(to) {
      if (to.name == 'classManage') {
        this.getTableQuery();
      }
    },
  },
}
</script>

<style scoped>
@import "../../assets/css/panel.css";

.context {
  display: block;
  margin: 0 auto;
  background-color: #fff !important;
  padding: 30px;
}

.panel-body {
  padding: 20px;
  background: #F0F2F5;
}

.change {
  width: 100%;
  overflow: hidden;
  display: block;
  margin: 0 auto;
  padding-top: 10px;
  padding-bottom: 10px;
}

.change button {
  float: left;
}

.change button.pull-right {
  float: right;
}

.dialogTitle {
  width: 100%;
  overflow: hidden;
  display: block;
  margin: 0 auto;
  color: #000000;
  font-size: 18px;
  text-align: center;
}

.dialogTitle em {
  float: none;
  font-style: normal;
  color: #3799FF;
  margin: 0;
}

/deep/ .el-transfer-panel__item .el-checkbox__input {
  left: 40px;
}

.dialogFooter {
  width: 90%;
  overflow: hidden;
  display: block;
  margin: 0 auto;
  margin-top: 10px;
}

.dialogFooter button {
  float: right;
  margin-left: 10px;
}

.dialogContent {
  width: 100%;
  overflow: hidden;
  display: block;
  margin: 0 auto;
}

.dialogContent .pull-left {
  width: 30%;
  float: left;
}

.dialogContent .pull-right {
  width: 70%;
  float: right;
}

.blueTitle {
  width: 200px;
  overflow: hidden;
  display: block;
  margin: 0 auto;
  margin-top: 10px;
  margin-bottom: 40px;
  background: #F0F2F5;
  border-radius: 19px;
  text-align: center;
  color: #3799FF;
  font-size: 16px;
  padding: 5px 24px;
}

.current {
  width: 158px;
  height: 23px;
  /*float: left;*/
  border-radius: 250px;
  text-align: center;
  background: #F0F2F5;
  color: #545454;
  font-size: 14px;
  padding: 3px 10px;
  margin-left: 20px;
}

.lessonSpan {
  width: 78px;
  height: 22px;
  border-radius: 11px;
  margin-right: 5px;
  float: left;
  margin-bottom: 3px;
  text-align: center;
  color: #000;
  font-size: 12px;
}

.classNames {
  width: 211px;
  height: 25px;
  background: #f0f2f5;
  font-family: "Source Han Sans CN";
  font-weight: normal;
  font-size: 16px;
  color: #3799ff;
  border-radius: 250px;
  text-align: center;
  margin: 0 auto;
  margin-bottom: 10px;
}

/deep/ .el-date-editor .el-range-separator {
  line-height: 25px;
}

.likeTab {
  width: 100%;
  overflow: hidden;
  display: block;
  margin: 0 auto;
  padding-top: 10px;
  padding-bottom: 0;
  border-bottom: 1px solid #ccc;
  margin-bottom: 10px;
}

.likeTab button {
  float: left;
  border-radius: 0;
}

.likeTab button.pull-right {
  float: right;
}

.el-dialog__body .el-date-editor.el-input__inner {
  width: 156px;
}

.el-transfer-panel__item.el-checkbox .el-checkbox__label {
  width: 156px;
}

/deep/ .el-dialog__body .el-transfer-panel__item .el-checkbox__input {
  left: 10px;
}

/deep/ .el-dialog__body .el-form-item__content .el-select {
  float: left;
  margin-left: 50px;
}

/deep/ .el-dialog__body .el-transfer {
  float: left;
  margin-left: 50px;
}

@media (min-width: 320px) and (max-width: 1367px) {
  .panel /deep/ .el-date-editor--daterange {
    max-width: 240px;
  }

  .panel /deep/ .el-date-editor .el-range-separator {
    line-height: 35px;
  }
}
</style>