<template>
  <div class="m-container">
    <h2>
      <div class="squrt"></div>学员列表
    </h2>
    <div class="m-core">
      <div class="newBand" v-permission="'studentManage/register'" @click="addStudent">新增学员</div>
      <div class="newBand" @click="onCreateQRCode">学员激活列表</div>
      <!-- 搜索标题 -->
      <el-form :inline="true" class="searchForm" v-model.trim="searchForm">
        <el-form-item>
          <el-input
            placeholder="学生姓名或电话"
            @keyup.enter.native="onSearch"
            v-model.trim="searchForm.search"
          ></el-input>
        </el-form-item>
        <el-form-item prop="organId">
          <el-select
            class="multiple"
            filterable
            v-model.trim="searchForm.organId"
            clearable
            placeholder="请选择分部"
          >
            <el-option
              v-for="(item,index) in organList"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="isActive">
          <el-select
            class="multiple"
            v-model.trim="searchForm.isActive"
            clearable
            placeholder="是否激活"
          >
            <el-option label="是" value="true"></el-option>
            <el-option label="否" value="false"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="hasCourse">
          <el-select
            class="multiple"
            v-model.trim="searchForm.hasCourse"
            clearable
            placeholder="是否有课"
          >
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="isMake">
          <el-select
            class="multiple"
            v-model.trim="searchForm.isMake"
            clearable
            placeholder="预约网管课"
          >
            <el-option label="是" value="true"></el-option>
            <el-option label="否" value="false"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="hasPracticeCourse">
          <el-select
            class="multiple"
            v-model.trim="searchForm.hasPracticeCourse"
            clearable
            placeholder="是否有网管课"
          >
            <el-option label="是" value="true"></el-option>
            <el-option label="否" value="false"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item>
          <el-input placeholder="学生姓名"
                    @keyup.enter.native='onSearch'
                    v-model.trim="searchForm.studentName"></el-input>
        </el-form-item>-->
        <el-form-item>
          <el-button @click="onSearch" type="danger">搜索</el-button>
          <el-button @click="onReSet" type="primary">重置</el-button>
          <el-button
            type="primary"
            v-permission="'export/studentHasCourse'"
            @click="downLoadStudent"
          >导出名单</el-button>
        </el-form-item>
      </el-form>
      <!-- 列表 -->
      <div class="tableWrap">
        <el-table :data="tableList" :header-cell-style="{background:'#EDEEF0',color:'#444'}">
          <el-table-column align="center" prop="userId" label="学员编号"></el-table-column>
          <el-table-column align="center" prop="username" label="学员姓名"></el-table-column>
          <el-table-column align="center" prop="organName" width="150px" label="所属分部"></el-table-column>
          <el-table-column align="center" label="性别">
            <template slot-scope="scope">{{ scope.row.gender ? '男': '女' }}</template>
          </el-table-column>
          <el-table-column align="center" prop="realName" label="家长姓名"></el-table-column>
          <el-table-column align="center" width="180px" prop="parentsPhone" label="家长联系电话"></el-table-column>
          <el-table-column align="center" label="是否激活">
            <template slot-scope="scope">{{ scope.row.isActive ? '是' : '否' }}</template>
          </el-table-column>
          <el-table-column align="center" label="是否有课">
            <template slot-scope="scope">{{ scope.row.hasCourse ? '是' : '否' }}</template>
          </el-table-column>
          <el-table-column align="center" label="预约网管课">
            <template slot-scope="scope">{{ scope.row.isMake ? '是' : '否' }}</template>
          </el-table-column>
          <el-table-column align="center" label="是否有网管课">
            <template slot-scope="scope">{{ scope.row.hasPracticeCourse ? '是' : '否' }}</template>
          </el-table-column>
          <el-table-column align="center" prop="courseBalance" label="课程余额(元)"></el-table-column>
          <el-table-column align="center" fixed="right" width="180px" label="操作">
            <template slot-scope="scope">
              <router-link
                style="color:#409EFF"
                v-permission="'/studentDetail'"
                :to="{path:`/business/studentDetail?userId=${scope.row.userId}`,query:{search:JSON.stringify(searchForm),rules:JSON.stringify(pageInfo)}}"
              >查看</router-link>
              <el-button
                type="text"
                v-permission="'studentManage/studentUpdate'"
                @click="resetStudent(scope.row)"
              >修改</el-button>
              <!-- api-auth/user/updatePassword2 -->
              <el-button
                v-permission="'api-auth/user/updatePassword2'"
                @click="resetPassWrod(scope.row)"
                type="text"
              >修改密码</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          :total="pageInfo.total"
          :page.sync="pageInfo.page"
          :limit.sync="pageInfo.limit"
          :page-sizes="pageInfo.page_size"
          @pagination="getList"
        />
      </div>
    </div>
    <el-dialog
      :title="maskName"
      width="700px"
      label-width="100px"
      label-position="right"
      class="studentInfo"
      :visible.sync="studentVisible"
    >
      <el-divider>基本信息</el-divider>
      <el-form
        :model="studentForm"
        :inline="true"
        label-width="80px"
        label-position="right"
        ref="studentForm"
        :rules="studentRules"
      >
        <el-form-item
          label="联系电话"
          prop="phone"
          :rules="[{ required: true, message: '请输入手机号' }, { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }]"
        >
          <!--   @blur="checkPhone(studentForm.phone)" -->
          <el-input v-model.trim="studentForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="所属分部" prop="organId">
          <el-select
            class="multiple"
            v-model.trim="studentForm.organId"
            filterable
            clearable
            placeholder="请选择分部"
          >
            <el-option
              v-for="(item,index) in organList"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学生姓名" prop="name">
          <el-input v-model.trim="studentForm.name"></el-input>
        </el-form-item>
        <el-form-item label="学生性别" prop="sex">
          <el-select
            class="multiple"
            filterable
            v-model.trim="studentForm.sex"
            clearable
            placeholder="请选择性别"
          >
            <el-option :value="0" label="女"></el-option>
            <el-option :value="1" label="男"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="家长姓名">
          <el-input v-model.trim="studentForm.parseName"></el-input>
        </el-form-item>

        <el-form-item label="出生日期">
          <el-date-picker
            v-model.trim="studentForm.date"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="studentVisible = false">取 消</el-button>
        <el-button type="primary" v-if="isNew" @click="submitAddStudent">确 定</el-button>
        <el-button type="primary" v-if="!isNew" @click="resetStudentSubmie">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="qrcodeStatus" center width="300px">
      <div class="right-code">
        <h2 class="title">学员激活列表</h2>
        <div id="qrcode" class="qrcode code" ref="qrCodeUrl"></div>
        <!-- <p class="code-url"
        v-if="codeUrl2">{{ codeUrl2 }}</p>-->
      </div>
    </el-dialog>
    <el-dialog
      title="修改密码"
      :visible.sync="passwrodVisiable"
      :before-close="closePassWord"
      width="400px"
    >
      <el-form :model="passwrodForm" ref="passwrodForm" :inline="true">
        <el-form-item
          label="手机号"
          prop="phone"
          label-width="80px"
          :rules="[{ required: true, message: '手机号不能为空',trigger: 'blur'},{pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号',trigger: 'blur' }]"
        >
          <el-input v-model.trim="passwrodForm.phone"></el-input>
        </el-form-item>
        <el-form-item
          label="输入密码"
          prop="password"
          label-width="80px"
          :rules="[{ required: true, message: '密码不能为空',trigger: 'blur'},{pattern:/^[\w]{6,20}$/,message:'密码为6-20位',trigger: 'blur'}]"
        >
          <el-input v-model.trim="passwrodForm.password"></el-input>
        </el-form-item>
        <el-form-item
          label="再次输入"
          prop="password2"
          label-width="80px"
          :rules="[{ required: true, message: '密码不能为空',trigger: 'blur'},{pattern:/^[\w]{6,20}$/,message:'密码为6-20位',trigger: 'blur'}]"
        >
          <el-input v-model.trim="passwrodForm.password2"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="passwrodVisiable = false">取 消</el-button>
        <el-button type="primary" @click="submitResetPassWord">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import pagination from "@/components/Pagination/index";
import {
  queryStudentList,
  getStudentInfoByPhone,
  registerStudent,
  updateStudent,
  studentHasCourse
} from "@/api/studentManager";
import { vaildStudentUrl } from "@/utils/validate";
import { getEmployeeOrgan, resetPassword2 } from "@/api/buildTeam";
import QRCode from "qrcodejs2";
import store from "@/store";
import axios from "axios";
import qs from "qs";
import { getToken } from "@/utils/auth";
import load from "@/utils/loading";
export default {
  name: "studentList",
  components: { pagination },
  data() {
    return {
      studentVisible: false,
      searchForm: {
        organId: null,
        search: null,
        studentName: null,
        isActive: null,
        hasCourse: null,
        isMake: null,
        hasPracticeCourse: null
      },
      searchList: [],
      tableList: [],
      organList: [],
      pageInfo: {
        // 分页规则
        limit: 10, // 限制显示条数
        page: 1, // 当前页
        total: 0, // 总条数
        page_size: [10, 20, 40, 50] // 选择限制显示条数
      },
      studentForm: {
        phone: "",
        organId: "",
        name: "",
        sex: "",
        parseName: "",
        date: "",
        nation: ""
      },
      studentRules: {
        name: [{ required: true, message: "请输入学生姓名" }],
        sex: [{ required: true, message: "请选择学生姓名" }],
        date: [{ required: true, message: "请选择出生日期" }],
        organId: [{ required: true, message: "请选择分部" }],
        nation: [{ required: true, message: "请输入名族" }]
      },
      isNew: false,
      active: null,
      maskName: "新增学员",
      qrcodeStatus: false,
      qrcodes: true,
      activeRow: null,
      passwrodVisiable: false,
      passwrodForm: {
        phone: "",
        password: "",
        password2: ""
      },
      activatedRow: null
    };
  },
  mounted() {
    if (this.$route.query.search) {
      this.$route.query.search instanceof Object
        ? (this.searchForm = this.$route.query.search)
        : (this.searchForm = JSON.parse(this.$route.query.search));
    }
    if (this.$route.query.rules) {
      this.$route.query.rules instanceof Object
        ? (this.pageInfo = this.$route.query.rules)
        : (this.pageInfo = JSON.parse(this.$route.query.rules));
    }
    getEmployeeOrgan().then(res => {
      if (res.code == 200) {
        this.organList = res.data;
      }
    });
    this.getList();
  },
  methods: {
    onSearch() {
      this.pageInfo.page = 1;
      this.getList();
    },
    onCreateQRCode() {
      // 生成报名二维码
      this.qrcodeStatus = true;
      // let id = this.$route.query.id
      // let teamName = this.$route.query.name

      setTimeout(() => {
        if (this.qrcodes) {
          this.qrcodes = false;
          this.qrcode = new QRCode("qrcode", {
            width: 250,
            height: 250,
            colorDark: "#000000",
            colorLight: "#ffffff",
            correctLevel: QRCode.CorrectLevel.H
          });
        }
        // vaildStudentUrl() + `/#/sporadicLogin?id=${刷刷刷}`
        this.qrcode.clear();
        this.qrcode.makeCode(vaildStudentUrl() + `/#/queryStudentPer`);
        // this.codeUrl = vaildStudentUrl() + '/#/login?musicGroupId=' + id
      }, 500);
    },
    getList() {
      let params = this.searchForm;
      params.rows = this.pageInfo.limit;
      params.page = this.pageInfo.page;
      params.organId ? params.organId : (params.organId = null);
      queryStudentList(params).then(res => {
        if (res.code == 200) {
          this.tableList = res.data.rows;
          this.pageInfo.total = res.data.total;
        }
      });
    },
    onReSet() {
      this.searchForm = {
        organId: null,
        search: null,
        studentName: null,
        isActive: null,
        isMake: null
      };
    },
    downLoadStudent () {
      let url = '/api-web/export/studentHasCourse'
      let searchForm = this.searchForm
      let data = {
        organId: searchForm.organId ? searchForm.organId : null,
        search: searchForm.search ? searchForm.search : null,
        isActive: searchForm.isActive ? searchForm.isActive : null,
        hasCourse: searchForm.hasCourse == "" ? null : searchForm.hasCourse,
        isMake: searchForm.isMake ? searchForm.isMake : null,
        hasPracticeCourse: searchForm.hasPracticeCourse
          ? searchForm.hasPracticeCourse
          : null
      };
      const options = {
        method: "POST",
        headers: {
          Authorization: getToken()
        },
        url,
        data: qs.stringify(data),
        responseType: "blob"
      };

      this.$confirm('确定导出学员名单?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        load.startLoading()
        axios(options).then(res => {
          let blob = new Blob([res.data], {
            // type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8',
            type: 'application/vnd.ms-excel;charset=utf-8'
            // word文档为application/msword,pdf文档为application/pdf,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8
          })
          let text = (new Response(blob)).text()
          text.then(res => {
            // 判断是否报错
            if(res.indexOf('code') != -1) {
              let json = JSON.parse(res)
              this.$message.error(json.msg)
            } else {
              let objectUrl = URL.createObjectURL(blob)
              let link = document.createElement("a")
              let nowTime = new Date()
              let ymd = nowTime.getFullYear() + (nowTime.getMonth() + 1) + nowTime.getDate()
              let fname = `导出学员名单` + ymd //下载文件的名字
              link.href = objectUrl
              link.setAttribute("download", fname)
              document.body.appendChild(link)
              link.click()
            }
          })
          
          load.endLoading();
        }).catch(error => {
            this.$message.error('导出数据失败，请连接管理员');
            load.endLoading();
          }) 
      }).catch(() => {});
    },
    checkPhone(val) {
      var regu = /^1[3456789]\d{9}$/;
      var re = new RegExp(regu);
      if (re.test(val)) {
        getStudentInfoByPhone({ mobile: this.studentForm.phone }).then(res => {
          if (res.code == 200) {
            if (res.data) {
              this.studentForm = {
                name: res.data.name,
                sex: res.data.gender,
                parseName: res.data.parentsName,
                // sound: parseInt(res.data.subjectId),
                phone: val,
                date: res.data.birthdate
              };
            }
          }
        });
      }
    },
    submitAddStudent() {
      // 效验  然后组数据提交
      this.$refs["studentForm"].validate(item => {
        if (item) {
          let obj = {
            phone: this.studentForm.phone,
            username: this.studentForm.name,
            gender: this.studentForm.sex,
            realName: this.studentForm.parseName,
            birthdate: this.studentForm.date,
            organId: this.studentForm.organId,
            nation: this.studentForm.nation
          };
          registerStudent(obj).then(res => {
            if (res.code == 200) {
              this.$message.success("添加成功");
              this.studentVisible = false;
              this.getList();
            }
          });
        }
      });
    },
    // 修改学生信息
    resetStudentSubmie() {
      this.$refs["studentForm"].validate(item => {
        if (item) {
          let obj = {
            phone: this.studentForm.phone,
            username: this.studentForm.name,
            gender: this.studentForm.sex,
            realName: this.studentForm.parseName,
            birthdate: this.studentForm.date,
            organId: this.studentForm.organId,
            id: this.active.userId,
            nation: this.studentForm.nation
          };
          updateStudent(obj).then(res => {
            if (res.code == 200) {
              this.$message.success("修改成功");
              this.studentVisible = false;
              this.getList();
            }
          });
        }
      });
    },
    addStudent() {
      this.isNew = true;
      this.studentVisible = true;
      this.maskName = "新增学员";
    },
    resetStudent(row) {
      this.isNew = false;
      this.active = row;
      this.studentVisible = true;
      this.maskName = "修改学员";
      this.studentForm = {
        phone: row.parentsPhone,
        name: row.username,
        sex: row.gender,
        parseName: row.realName,
        date: row.birthdate,
        organId: row.organId,
        nation: row.nation
      };
    },
    resetPassWrod(row) {
      this.activatedRow = row;
      this.passwrodForm.phone = row.parentsPhone;
      this.passwrodVisiable = true;
    },
    closePassWord() {
      this.activatedRow = null;
      this.passwrodForm = {
        phone: "",
        password: "",
        password2: ""
      };
      this.$refs["passwrodForm"].resetFields();
      this.passwrodVisiable = false;
    },
    submitResetPassWord() {
      if (this.passwrodForm.password !== this.passwrodForm.password2) {
        this.$message.error("两次密码必须相同");
        return;
      }
      this.$refs["passwrodForm"].validate(res => {
        if (res) {
          // 发请求
          resetPassword2({
            mobile: this.passwrodForm.phone,
            newPassword: this.passwrodForm.password,
            userId: this.activatedRow.userId
          }).then(res => {
            if (res.code == 200) {
              // 修改成功
              this.$message.success("修改成功");
              this.closePassWord();
            }
          });
        }
      });
    }
  },
  watch: {
    studentVisible(val) {
      if (!val) {
        this.studentForm = {
          phone: "",
          organId: "",
          name: "",
          sex: "",
          parseName: "",
          date: "",
          nation: ""
        };
        this.$refs["studentForm"].resetFields();
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.newBand {
  display: inline-block;
  margin-right: 10px;
}
.right-code {
  // width: 50%;
  // float: left;
  .title {
    font-size: 18px;
    text-align: center;
    padding-bottom: 8px;
  }
}
/deep/.studentInfo {
  .el-dialog__body {
    padding-top: 0;
    padding-bottom: 0;
  }
  .multiple.el-select {
    width: 100% !important;
  }
}
</style>
