<template>
  <div class="dashboard-container">
    <transition name="fade">
      <div class="left">
        <el-form :inline="true"
                 :model="sectionForm"
                 class="sectionForm">
          <el-form-item>
            <el-select v-model="sectionForm.section"
                       placeholder="请选择分部"
                       @change="chioseSection">
              <el-option v-for="(item,index) in brancheList"
                         :key="index"
                         :value="item.branchId"
                         :label="item.branchName"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <h2 v-if="MajorList.length > 0">所属乐团</h2>
        <ul>
          <!-- MajorList -->
          <li :class="activeMarjorId == item.id?'active':''"
              v-for="(item,index) in MajorList"
              :key="index"
              @click="chioseMajor(item.name,item.id,item.status)">{{ item.name }}</li>
        </ul>
      </div>
    </transition>
    <div class="right">
      <!-- 顶部收索框 -->
      <el-form :inline="true"
               class="topWrap"
               :model="topForm">
        <el-form-item label="学生姓名">
          <el-input v-model="topForm.team"
                    placeholder="请输入学生名称" />
        </el-form-item>
        <el-form-item label="学生专业">
          <el-select v-model="topForm.major"
                     placeholder="请输入学生专业">
            <el-option v-for="(item,index) in chioseList"
                       :key="index"
                       :value="item.subId"
                       :label="item.subName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学生状态">
          <el-select v-model="topForm.status"
                     placeholder="请选择学生状态"
                     clearable>
            <!-- // 1报名中，2缴费中，3报名截止，4已开团 -->
            <el-option :value="0"
                       label="报名中"></el-option>
            <el-option :value="1"
                       label="报名完成"></el-option>
            <el-option :value="2"
                       label="报名失败"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="学生">
          <el-input v-model="topForm.student"
                    placeholder="请输入学生姓名" />
        </el-form-item>-->
        <el-button type="primary"
                   icon="el-icon-search"
                   plain
                   @click="getstudentList">搜索</el-button>
        <el-button type="success"
                   icon="el-icon-refresh"
                   plain
                   @click="resetStudentList">重置</el-button>
        <el-button icon="el-icon-s-tools"
                   plain
                   v-if="majorStatus == 1 || majorStatus == 2"
                   @click="showFade('','','','')">批量调剂</el-button>

        <!--  v-if="majorStatus == 1" -->
        <el-button type='danger'
                   icon='el-icon-position'
                   v-show="paymentStatus"
                   @click="getMoney">开启缴费</el-button>
        <el-button type='warning'
                   icon="el-icon-news"
                   v-if='this.majorId'
                   @click='openUrl'>打开二维码</el-button>
        <el-button plain
                   @click="exportis">导出</el-button>
      </el-form>
      <!-- 提示语 -->
      <p class="subMsg"
         v-if="!majorId">请先选择分部和乐团后,再查看学生列表或者搜索学生~</p>
      <!-- 列表 -->
      <div class="tableWrap"
           v-if="majorId">
        <el-table :data="tableData"
                  style="width: 100%"
                  id='tableid'
                  @selection-change="handleSelectionChange">
          <el-table-column type="selection"
                           :selectable='checkboxT'
                           width="55"
                           v-if='this.majorStatus <= 2'>

          </el-table-column>
          <el-table-column prop="city"
                           align="center"
                           label="所属分部"></el-table-column>
          <el-table-column prop="name"
                           align="center"
                           label="学生姓名"></el-table-column>
          <el-table-column prop="sex"
                           align="center"
                           label="性别"
                           :formatter="filterSex"></el-table-column>
          <el-table-column prop="birthday"
                           align="center"
                           label="出生日期"
                           :formatter="filterDate"></el-table-column>
          <el-table-column prop="class"
                           align="center"
                           label="班级"
                           :formatter="filterClass"></el-table-column>
          <el-table-column prop="school"
                           align="center"
                           label="单位/学校"></el-table-column>
          <el-table-column prop="patriarchPhone"
                           align="center"
                           label="联系方式"></el-table-column>
          <el-table-column prop="subName"
                           align="center"
                           label="录取专业"></el-table-column>
          <el-table-column prop="patriarchName"
                           align="center"
                           label="家长姓名"></el-table-column>
          <el-table-column prop="patriarchUnit"
                           align="center"
                           label="家长工作单位"></el-table-column>
          <!-- <el-table-column prop="musical" align="center" label="乐器准备方式"></el-table-column> -->
          <!-- status -->
          <el-table-column prop="status"
                           align="center"
                           label="状态"
                           :formatter="filterStatus"></el-table-column>
          <el-table-column prop="amount"
                           align="center"
                           label="实际缴费金额"></el-table-column>
          <el-table-column align="center"
                           label="操作">
            <template slot-scope="scope">
              <div>
                <!-- 学生id crouseId subId -->
                <el-button type="primary"
                           plain
                           :disabled='!disabled'
                           @click="showFade(scope.row.id,scope.row.courseId,scope.row.subId,scope.row.status)">调剂</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 调剂弹出层 -->
        <el-dialog title="提示"
                   :visible.sync="dialogVisible"
                   width="30%">
          <span>请选择调剂乐团</span>
          <el-select v-model="reviseMajor"
                     placeholder="请选择调剂课程"
                     @change="reviseMajors">
            <el-option v-for="(item,index) in chioseList"
                       :key="index"
                       :value="item.subId+'-'+item.id"
                       :label="item.subName"></el-option>
          </el-select>
          <span slot="footer"
                class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary"
                       @click="submitRe">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 分页器 -->
        <div class="paginationWrap">
          <el-pagination background
                         class="pagination"
                         layout="prev, pager, next"
                         :total="total"
                         :current-page.sync="currentPage"
                         :page-size.sync="limit"
                         @current-change="handleCurrentChange"></el-pagination>
        </div>
      </div>
    </div>
    <el-dialog title="二维码"
               :visible.sync="code"
               width="30%">
      <div class="wrap">
        <div id="qrCode"
             ref="qrCodeDiv"></div>
      </div>

    </el-dialog>

    <!-- 弹出框 -->
    <el-dialog title="提示:请输入短信模板"
               :visible.sync="isDialog"
               width="30%">
      <el-form v-model="dialogForm">
        <el-form-item>
          <el-input type="textarea"
                    :disabled="isRadioDisabled"
                    :rows="3"
                    v-model="dialogForm.text"
                    placeholder="请输入短信模板"></el-input>
        </el-form-item>
      </el-form>
      <div class="radioWrap"
           style="margin-top:20px">
        <el-radio v-model="radio"
                  :label="1">线上</el-radio>
        <el-radio v-model="radio"
                  :label="2">线下</el-radio>
      </div>

      <span slot="footer"
            class="dialog-footer">
        <el-button type="primary"
                   @click="gotoMoneyok">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
import qs from "qs";
// import { loading } from "element-ui";
import { scrollTo } from '@/utils/scroll-to'
import QRCode from 'qrcodejs2'
import {
  getAllMajor,
  getMusicTeams,
  getBranches,
  getStudentList,
  updateUser,
  updateClass
} from "@/api/table";
import { setTimeout } from "timers";
export default {
  name: "dashboard",
  data () {
    return {
      paymentStatus: false, // 开启缴费开关
      topForm: {
        team: "",
        status: "",
        student: "",
        major: ''

      },
      sectionForm: {
        section: ""
      },
      MajorList: [], // 所有乐团集合
      tableData: [
      ],
      isMusic: true,
      dialogVisible: false,
      reviseMajor: "", // 选择的团名
      actionTearm: "", // 选中的乐团名字
      majorStatus: "", // 所选乐团的状态
      majorId: "", // 所选乐团的ID
      chioseList: [], // 所有调剂科目的集合
      sessionId: "",
      brancheList: [], // 所有分部集合
      limit: 20,
      total: 0,
      page: 1,
      studentId: "", // 学生id
      courseId: "", // 当前选中的课程
      subId: "", // 当前选中的项目
      disabled: true, // 判断单个调剂按钮能否点击
      activeMarjorId: '-1', // 选中乐团的id
      studentStatus: '-1', //单个学生调剂时学生状态
      isDialog: false, // 显示隐藏弹框
      radio: 2, // 线上线下的选择框
      isRadioDisabled: false,
      dialogForm: {
        text: ''
      },
      code: false,
      first: true,
      qrcodes: ''
    };
  },
  methods: {
    showFade (id, courseId, subId, status) {
      if (status == 1) {
        this.$message.error('此学生已报名成功,无法调剂');
        return;
      }
      if (id && courseId) {
        this.studentId = id;
        this.courseId = courseId;
      }
      this.subId = subId;
      this.dialogVisible = true;

    },
    // 获取分类选项卡
    getMajors () {
      // classid  乐团id
      getAllMajor(qs.stringify({ clazzId: this.majorId }))
        .then(res => {
          if (res.code == 200) {
            this.chioseList = res.data;
          }
        })
        .catch(res => {

        });
    },
    // 获取所有乐团列表
    getMusicTeam (id, row) {
      getMusicTeams(qs.stringify({ branchId: id, row, page: this.page })).then(
        res => {
          if (res.code == 200) {
            this.MajorList = res.data.rows;
          }
        }
      );
    },
    // 获取所有分部
    getBranches () {
      getBranches().then(res => {
        if (res.code == 200) {
          this.brancheList = res.data;
        }
      });
    },
    // 点击选择分部
    chioseSection (id) {
      // 查询分部列表
      // console.log(id);
      this.sessionId = id;
      this.getMusicTeam(id, 50);
    },
    // 点击分部下的乐团
    chioseMajor (name, id, status) {
      this.activeMarjorId = id;
      this.actionTearm = name;
      this.majorStatus = status;
      if (status == 3 || status == 4) {
        this.disabled = false;
      }
      // 判断乐团是否已经开启缴费
      if (status == 2 || status == 3 || status == 4) {
        this.paymentStatus = false
      } else {
        this.paymentStatus = true
      }
      this.majorId = id;
      // 发请求 获取学生列表数据
      this.getstudentList();
      // 获取分类选项卡
      this.getMajors();
    },
    // 获取学生列表(查询也用这个接口)
    getstudentList () {
      if (!this.majorId) {
        this.$message.error("请先选择分部与乐团在搜索学生");
        return;
      }
      getStudentList(
        qs.stringify({
          musicTeamId: this.majorId,
          name: this.topForm.team,
          status: this.topForm.status,
          subId: this.topForm.major,
          page: this.page,
          rows: this.limit
        })
      ).then(res => {
        this.tableData = res.data.rows;
        this.total = res.data.total;
        this.pageSize = res.data.limit;
      });
    },
    // 重置搜索
    resetStudentList () {
      this.topForm.team = "";
      this.topForm.status = "";
      this.topForm.major = "";
      this.page = 1;
      this.getstudentList();
    },
    // 性别分类过滤器
    filterSex (val) {
      let arr = ["男", "女"];
      return arr[val.sex];
    },
    // 时间格式化过滤器
    filterDate (val) {
      let str = "";
      val.birthday ? (str = val.birthday.split(" ")[0]) : (str = "");
      return str;
    },
    // 格式化班级
    filterClass (val) {
      return val.grade + val.gclass;
    },
    // 格式化状态
    filterStatus (val) {
      let arr = ["报名中", "报名完成", "报名失败"];
      return arr[val.status];
    },
    // 修改科目触发事件
    reviseMajors (val) {
      // 这里切割字符串 拿到想要的数据
      if (val) {
        this.subId = val.split('-')[0];
        this.crouseId = val.split('-')[1];
      }
    },
    // 确认修改
    submitRe () {
      // console.log(this.crouseId);
      updateUser(
        qs.stringify({
          courseId: this.crouseId,
          subId: this.subId,
          userId: this.studentId
        })
      ).then(res => {
        if (res.code == 200) {
          this.dialogVisible = false;
          this.$message.success(res.msg);
          this.reviseMajor = "";
          // 刷新列表
          this.getstudentList();
        }
      });
    },
    // 点击开始缴费 1报名中，2缴费中，3报名截止，4已开团
    getMoney () {
      this.isDialog = true;
    },
    handleCurrentChange (val) {
      this.page = val;
      // this.limit = pageSize;
      this.getstudentList();
      // if (this.autoScroll) {
      scrollTo(0, 800);
      // }
    },
    handleSelectionChange (val) {
      let str = '';
      if (val.length >= 2) {
        this.disabled = false;
      } else {
        this.disabled = true;
      }
      if (val.length > 0) {
        val.forEach(item => {
          str += item.id + ','
        })
      }
      str = str.substring(0, str.length - 1);
      this.studentId = str;

    },
    checkboxT (row) {
      // console.log(this.majorStatus > 2);
      if (row.status == 1 || this.majorStatus > 2) {
        return false;
      } else {
        return true;
      }
    },
    // 点击打开报名链接
    openUrl () {
      // debugger
      this.code = true;
      this.qrcode();
      // window.open(`https://pay.dayaedu.com/#/order?classId=${this.majorId}&schoolName=${this.actionTearm}`)
    },
    gotoMoneyok () {
      let val = this.dialogForm.text;
      if (this.radio != 1) {
        // 线上

        if (!val.trim()) {
          this.$message.error('请输入短信模板');
          return;
        }
      }

      updateClass(qs.stringify({ id: this.majorId, smsMsg: val, type: this.radio })).then(res => {
        if (res.code == 200) {
          this.$message.success("乐团报名成功请尽快缴费");
          setTimeout(() => {
            this.getstudentList();
            this.majorStatus = 2;
            this.isDialog = false;
            this.dialogForm.text = '';
          }, 1000);
        } else {
          this.$message.error(res.msg)
        }
      });
    },
    qrcode () {

      setTimeout(() => {
        this.qrcodes = new QRCode(document.getElementById("qrCode"), {
          width: 200, // 设置宽度，单位像素
          height: 200, // 设置高度，单位像素
          text: `http://testpay.dayaedu.com/#/order?classId=${this.majorId}&schoolName=${this.actionTearm}` // 设置二维码内容或跳转地址
        })
      }, 100)
      if (document.getElementById("qrCode")) {
        document.getElementById("qrCode").innerHTML = ''
      }

    },
    exportis () {
      // var curTbl = document.getElementById('tableid');
      // this.tableId = curTbl;
      // console.log(curTbl);
      console.log(this.tableData)
      if (this.tableData.length <= 0) {
        return false
      }
      this.method5('tableid');
    },

    // 导出
    getExplorer () {
      var explorer = window.navigator.userAgent;
      //ie
      if (explorer.indexOf("MSIE") >= 0) {
        return 'ie';
      }
      //firefox
      else if (explorer.indexOf("Firefox") >= 0) {
        return 'Firefox';
      }
      //Chrome
      else if (explorer.indexOf("Chrome") >= 0) {
        return 'Chrome';
      }
      //Opera
      else if (explorer.indexOf("Opera") >= 0) {
        return 'Opera';
      }
      //Safari
      else if (explorer.indexOf("Safari") >= 0) {
        return 'Safari';
      }
    },
    method5 (tableid) {

      if (this.getExplorer() == 'ie') {
        var curTbl = document.getElementById(tableid);
        var oXL = new ActiveXObject("Excel.Application");
        var oWB = oXL.Workbooks.Add();
        var xlsheet = oWB.Worksheets(1);
        var sel = document.body.createTextRange();
        sel.moveToElementText(curTbl);
        sel.select();
        sel.execCommand("Copy");
        xlsheet.Paste();
        oXL.Visible = true;
        try {

          var fname = oXL.Application.GetSaveAsFilename("哈哈哈.xls", "Excel Spreadsheets (*.xls), *.xls");
        } catch (e) {
          print("Nested catch caught " + e);
        } finally {
          oWB.SaveAs(fname);
          oWB.Close(savechanges = false);
          oXL.Quit();
          oXL = null;
          this.idTmr = window.setInterval("Cleanup();", 1);
        }

      }
      else {
        this.tableToExcel();
      }
    },
    Cleanup () {
      window.clearInterval(this.idTmr);
      this.CollectGarbage();
    },
    tableToExcel () {

      (function () {
        var uri = 'data:application/vnd.ms-excel;base64,',
          template = '<html><head><meta charset="UTF-8"></head><body><table>{table}</table></body></html>',
          base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) },
          format = function (s, c) {
            return s.replace(/{(\w+)}/g,
              function (m, p) { return c[p]; })          }
        // table name
        let table = document.getElementById('tableid')
        // || name
        var ctx = { worksheet: 'Worksheet', table: table.innerHTML }
        window.location.href = uri + base64(format(template, ctx))
        // 
        // return function () {


        // }
      })()
    },
  },
  watch: {
    radio (val) {
      if (val == 1) {
        this.isRadioDisabled = true;
      } else {
        this.isRadioDisabled = false;
      }
    }
  },
  computed: {
    currentPage: {
      get () {
        return this.page
      },
      set (val) {
        this.$emit('update:page', val)
      }
    },
  },
  mounted () {
    // 获取所有分部
    this.getBranches();
    //  获取所有学生列表
    // this.getstudentList();
  }
};
</script>

<style scoped>
.dashboard-container {
  padding-left: 10px;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  flex-wrap: nowrap;
}
.dashboard-container .left {
  width: 200px;
  min-height: 100vh;
  /* background-color: #14928a; */
  padding-top: 15px;
  border-right: 1px solid #ccc;
}
.dashboard-container .left h2 {
  margin-top: 15px;
  height: 40px;
  line-height: 40px;
  font-size: 18px;
  text-align: center;
  margin: 0;
  padding: 0;
  color: #333;
}
.dashboard-container .right {
  padding: 15px 0;
  width: calc(100% - 200px);
}
.topWrap {
  margin-left: 40px;
}
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
  opacity: 0;
}
.left ul {
  margin: 0;
  padding: 0;
}
.left li {
  display: block;
  text-align: center;
  list-style: none;
  color: #333;
  font-size: 14px;
  line-height: 70px;
  cursor: pointer;
}
.left li.active {
  color: #ffc10d;
}
.paginationWrap {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
}
.pagination {
  margin-top: 20px;
}
.joinBtn {
  position: fixed;
  right: 30px;
  top: 700px;
  z-index: 100;
}
.sectionForm {
  display: flex;
  flex-direction: row;
  justify-content: center;
}
.subMsg {
  width: 100%;
  text-align: center;
  font-size: 14px;
  color: #ccc;
  margin-top: 100px;
}
.wrap {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}
</style>
