<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>
      <!-- 搜索标题 -->
      <save-form
        :inline="true"
        class="searchForm"
        @submit="onSearch"
        @reset="onReSet"
        :model.sync="searchForm"
      >
        <el-form-item>
          <el-input
            clearable
            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 selects.branchs"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <remote-search
            :commit="'setTeachers'"
            v-model="searchForm.teacherId"
          />
          <!-- <el-select
            placeholder="指导老师"
            v-model="searchForm.teacherId"
            clearable
            filterable
          >
            <el-option
              v-for="(item, index) in selects.teachers"
              :label="item.realName"
              :value="item.id"
              :key="index"
            ></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="operatingTag">
          <el-select
            class="multiple"
            v-model.trim="searchForm.operatingTag"
            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="serviceTag">
          <el-select
            class="multiple"
            v-model.trim="searchForm.serviceTag"
            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="carePackage">
          <el-select
            class="multiple"
            v-model.trim="searchForm.carePackage"
            clearable
            placeholder="关心包"
          >
            <el-option label="不可用" :value="0"></el-option>
            <el-option label="可用" :value="1"></el-option>
            <el-option label="已使用" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="comeOnPackage">
          <el-select
            class="multiple"
            v-model.trim="searchForm.comeOnPackage"
            clearable
            placeholder="加油包"
          >
            <el-option label="不可用" :value="0"></el-option>
            <el-option label="可用" :value="1"></el-option>
            <el-option label="已使用" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button native-type="submit" type="danger">搜索</el-button>
          <el-button native-type="reset" type="primary">重置</el-button>
          <el-button
            type="primary"
            v-permission="'export/studentHasCourse'"
            @click="downLoadStudent"
            >导出名单</el-button
          >
        </el-form-item>
      </save-form>
      <!-- 列表 -->
      <div class="tableWrap">
        <el-table
          :data="tableList"
          :header-cell-style="{ background: '#EDEEF0', color: '#444' }"
        >
          <el-table-column align="center" prop="userId" label="学员编号">
            <template slot-scope="scope">
              <copy-text>{{ scope.row.userId }}</copy-text>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="username" label="学员姓名">
            <template slot-scope="scope">
              <copy-text>{{ scope.row.username }}</copy-text>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="organName" label="所属分部">
            <template slot-scope="scope">
              <copy-text>{{ scope.row.organName }}</copy-text>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="cooperationOrganName"
            label="所属学校"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="subjectName"
            label="声部"
          ></el-table-column>
          <el-table-column align="center" prop="teacherName" label="指导老师">
            <template slot-scope="scope">
              <copy-text>{{ scope.row.teacherName }}</copy-text>
            </template>
          </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="120px"
            prop="parentsPhone"
            label="家长联系电话"
          ></el-table-column>
              <!-- <el-table-column
            align="center"
            prop="leaveNum"
            label="本月请假次数"
          ></el-table-column> -->
          <el-table-column align="center">
            <template slot="header">
              <p style="position: relative">
                是否激活
                <el-tooltip placement="top" popper-class="mTooltip">
                  <div slot="content">学员是否设置密码</div>
                  <i
                    class="el-icon-question"
                    style="font-size: 18px; color: #f56c6c"
                  ></i>
                </el-tooltip>
              </p>
            </template>
            <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.noStartPracticeCourseNum
            }}</template>
          </el-table-column>
               <el-table-column align="center" label="vip课剩余课时">
            <template slot-scope="scope">{{
              scope.row.noStartVipCourseNum
            }}</template>
          </el-table-column>
          <el-table-column align="center" label="是否运营">
            <template slot-scope="scope">{{
              scope.row.operatingTag ? "是" : "否"
            }}</template>
          </el-table-column>
          <el-table-column align="center" label="是否服务">
            <template slot-scope="scope">{{
              scope.row.serviceTag ? "是" : "否"
            }}</template>
          </el-table-column>
          <el-table-column align="center" label="是否是新用户">
            <template slot="header">
              <p style="position: relative">
                是否是新用户
                <el-tooltip placement="top" popper-class="mTooltip">
                  <div slot="content">
                    没有有效的VIP课程或未参与2020年双十一活动的用户为新用户
                  </div>
                  <i
                    class="el-icon-question"
                    style="font-size: 18px; color: #f56c6c"
                  ></i>
                </el-tooltip>
              </p>
            </template>
            <template slot-scope="scope">
              {{ scope.row.isNewUser ? "是" : "否" }}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="courseBalance"
            label="课程余额(元)"
          >
            <template slot-scope="scope">
              <div>
                {{ scope.row.courseBalance | moneyFormat }}
              </div>
            </template>
          </el-table-column>
                 <el-table-column
            align="center"
            prop="balance"
            label="账户余额(元)"
          >
            <template slot-scope="scope">
              <div>
                {{ scope.row.balance | moneyFormat }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="carePackage"
            label="关心包"
          >
            <template slot-scope="scope">{{ scope.row.carePackage | studentPackage }}</template>
          </el-table-column>
          <el-table-column align="center" prop="comeOnPackage" label="加油包">
            <template slot-scope="scope">{{
              scope.row.comeOnPackage | studentPackage
            }}</template>
          </el-table-column>
          <el-table-column
            align="center"
            fixed="right"
            width="250px"
            label="操作"
          >
            <template slot-scope="scope">
              <router-link
                v-permission="'/studentDetail'"
                class="el-button--text"
                :to="{
                  path: `/business/studentDetail`,
                  query: { ...scope.row },
                }"
                >查看</router-link
              >
              <el-button
                type="text"
                style="padding-left: 10px"
                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
              >
              <el-button
                v-if="scope.row.isSignedContract"
                type="text"
                @click="lookContracts(scope.row)"
                v-permission="'sysUserContracts/getLatest'"
                >下载协议</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <pagination
          sync
          :total.sync="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-position="right"
      class="studentInfo"
      @close="onMaskClose('studentForm')"
      :close-on-click-modal="false"
      :visible.sync="studentVisible"
    >
      <el-form
        :model="studentForm"
        :inline="true"
        label-width="130px"
        label-position="right"
        ref="studentForm"
        :rules="studentRules"
      >
        <el-alert
          title="课程信息"
          type="info"
          :closable="false"
          style="margin-bottom: 15px"
        ></el-alert>
        <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="1" label="男"></el-option>
            <el-option :value="0" label="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出生日期" prop="date">
          <el-date-picker
            v-model.trim="studentForm.date"
            style="width: 185px"
            value-format="yyyy-MM-dd"
            type="date"
            :picker-options="{
              firstDayOfWeek: 1,
            }"
            placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="学生声部" prop="subjectIdList">
          <el-select
            v-model.trim="studentForm.subjectIdList"
            filterable
            clearable
            placeholder="学员声部"
          >
            <el-option-group
              v-for="group in subjectList"
              :key="group.label"
              :label="group.label"
            >
              <el-option
                v-for="item in group.options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-option-group>
          </el-select>
        </el-form-item>
        <el-form-item label="家长姓名" prop="parseName">
          <el-input v-model.trim="studentForm.parseName"></el-input>
        </el-form-item>
        <el-form-item
          label="联系电话"
          prop="phone"
          :rules="[
            { required: true, message: '请输入手机号' },
            {
              pattern: /^1\d{10}$/,
              message: '请输入正确的手机号',
              trigger: 'blur',
            },
          ]"
        >
          <!--   @blur="checkPhone(studentForm.phone)" -->
          <el-input :maxlength="11" 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="请选择分部"
            @change="changeStudentOrgan"

          >
            <el-option
              v-for="(item, index) in selects.branchs"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="school" label="所属学校">
          <el-select v-model.trim="studentForm.school" filterable clearable  :disabled='!studentForm.organId'   class="multiple">
            <el-option
              v-for="(item, index) in cooperationList"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="指导老师" prop="teacherId">
          <el-select
            class="multiple"
            v-model.trim="studentForm.teacherId"
            clearable
            filterable
          >
            <el-option
              v-for="(item, index) in maskTeacherList"
              :label="item.realName"
              :value="item.id"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-alert
          title="课程信息"
          type="info"
          :closable="false"
          style="margin-bottom: 15px"
        ></el-alert>
        <el-form-item label="是否运营" prop="operatingTag">
          <el-select
            class="multiple"
            v-model.trim="studentForm.operatingTag"
            clearable
          >
            <el-option :value="1" label="是"></el-option>
            <el-option :value="0" label="否"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否服务" prop="serviceTag">
          <el-select
            class="multiple"
            v-model.trim="studentForm.serviceTag"
            clearable
          >
            <el-option :value="1" label="是"></el-option>
            <el-option :value="0" label="否"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否是新用户" prop="isNewUser">
          <template #label>
            <p style="position: relative; display: inline-block">
              是否是新用户
              <el-tooltip placement="top" popper-class="mTooltip">
                <div slot="content">
                  没有有效的VIP课程或未参与2020年双十一活动的用户为新用户
                </div>
                <i
                  class="el-icon-question"
                  style="font-size: 18px; color: #f56c6c"
                ></i>
              </el-tooltip>
            </p>
          </template>
          <el-select
            class="multiple"
            v-model.trim="studentForm.isNewUser"
            clearable
          >
            <el-option :value="1" label="是"></el-option>
            <el-option :value="0" label="否"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关心包" prop="carePackage">
          <el-select
            class="multiple"
            v-model.trim="studentForm.carePackage"
            clearable
            :disabled="!isNew && studentUpdatePackage.carePackage == 2"
            placeholder="请选择关心包"
          >
            <el-option label="不可用" :value="0"></el-option>
            <el-option label="可用" :value="1"></el-option>
            <el-option disabled label="已使用" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="加油包" prop="comeOnPackage">
          <el-select
            class="multiple"
            v-model.trim="studentForm.comeOnPackage"
            clearable
            :disabled="!isNew && studentUpdatePackage.comeOnPackage == 2"
            placeholder="请选择加油包"
          >
            <el-option label="不可用" :value="0"></el-option>
            <el-option label="可用" :value="1"></el-option>
            <el-option disabled label="已使用" :value="2"></el-option>
          </el-select>
        </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>
    <!-- 学员激活列表 -->
    <qr-code v-model="qrcodeStatus" title="学员激活列表" :codeUrl="qrcodeUrl" />

    <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="120px"
          :rules="[
            { required: true, message: '手机号不能为空', trigger: 'blur' },
            {
              pattern: /^1\d{10}$/,
              message: '请输入正确的手机号',
              trigger: 'blur',
            },
          ]"
        >
          <copy-text>{{ passwrodForm.phone }}</copy-text>
        </el-form-item>
        <el-form-item
          label="输入密码"
          prop="password"
          label-width="120px"
          :rules="[
            { required: true, message: '密码不能为空', trigger: 'blur' },
            {
              pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{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="120px"
          :rules="[
            { required: true, message: '密码不能为空', trigger: 'blur' },
            {
              pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{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>

    <el-dialog title="协议下载" :visible.sync="protocolVisible" width="650px">
      <div v-if="protocolVisible">
        <!-- <el-alert
          title="点击下载"
          :closable="false"
          type="info">
        </el-alert>
        <p style="font-size: 14px; color: #14928A; line-height: 1.5; padding: 8px 16px; cursor: pointer;" v-for="item in protocolVersions" :key="item.id" @click="onDownloadProtocol(item)">
          产品与服务协议{{ item.version == 2 ? "（含课程）" : "（含系统）" }}
        </p> -->
        <el-table
          style="width: 100%"
          :header-cell-style="{ background: '#EDEEF0', color: '#444' }"
          :data="protocolVersions"
        >
          <el-table-column align="center" prop="studentId" label="协议名称">
            <template slot-scope="scope">
              产品与服务协议{{ formatProtocol(scope.row.version) }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="签署时间" prop="createTime">
          </el-table-column>
          <el-table-column align="center" width="150px" label="操作">
            <template slot-scope="scope">
              <div>
                <el-button type="text" @click="onDownloadProtocol(scope.row)"
                  >下载</el-button
                >
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="protocolVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import pagination from "@/components/Pagination/index";
import {
  queryStudentList,
  getStudentInfoByPhone,
  registerStudent,
  updateStudent,
  studentHasCourse,
  getLatest,
} from "@/api/studentManager";
import { queryByOrganId } from "@/api/systemManage";
import qrCode from "@/components/QrCode/index";
import cleanDeep from "clean-deep";
import { vaildStudentUrl } from "@/utils/validate";
import { getEmployeeOrgan, resetPassword2, getTeacher } from "@/api/buildTeam";
import { subjectListTree } from "@/api/specialSetting";
import axios from "axios";
import qs from "qs";
import { packageStatus } from "@/constant/index";
import { getToken } from "@/utils/auth";
import load from "@/utils/loading";
import { permission } from "@/utils/directivePage";
export default {
  name: "studentList",
  components: { pagination, qrCode },
  data() {
    return {
      studentVisible: false,
      searchForm: {
        organId: null,
        search: null,
        studentName: null,
        isActive: null,
        hasCourse: null,
        // isMake: null,
        hasPracticeCourse: null,
        operatingTag: null,
        serviceTag: null,
        teacherId: null,
        carePackage: null,
        comeOnPackage: null,
      },
      searchList: [],
      tableList: [],
      organList: [],
      teacherList: [],
      maskTeacherList: [],
      subjectList: [], // 声部列表
      pageInfo: {
        // 分页规则
        limit: 10, // 限制显示条数
        page: 1, // 当前页
        total: 0, // 总条数
        page_size: [10, 20, 40, 50], // 选择限制显示条数
      },
      studentForm: {
        phone: "",
        organId: "",
        name: "",
        sex: "",
        parseName: "",
        date: "",
        serviceTag: null,
        operatingTag: null,
        teacherId: null,
        subjectIdList: null,
        isNewUser: null,
        carePackage: 0,
        comeOnPackage: 0,
        school:null
      },
      studentUpdatePackage: {
        carePackage: 0,
        comeOnPackage: 0,
      },
      studentRules: {
        name: [{ required: true, message: "请输入学生姓名" }],
        sex: [{ required: true, message: "请选择学生性别" }],
        date: [{ required: true, message: "请选择出生日期" }],
        organId: [{ required: true, message: "请选择分部" }],
        subjectIdList: [{ required: true, message: "请选择声部" }],
        serviceTag: [{ required: true, message: "请选择是否参与服务" }],
        isNewUser: [{ required: true, message: "请选择是否是新用户" }],
        operatingTag: [{ required: true, message: "请选择是否参与运营" }],
        teacherId: [{ required: true, message: "请选择指导老师" }],
      },
      isNew: false,
      active: null,
      maskName: "新增学员",
      qrcodeStatus: false,
      qrcodeUrl: null,
      activeRow: null,
      passwrodVisiable: false,
      passwrodForm: {
        phone: "",
        password: "",
        password2: "",
      },
      activatedRow: null,
      protocolVisible: false,
      protocolVersions: [],
      cooperationList: [],
    };
  },
  mounted() {
    this.$store.dispatch("setBranchs");
    this.$store.dispatch("setTeachers");
    this.getList();
  },
  methods: {
    onSearch() {
      this.pageInfo.page = 1;
      this.getList();
    },
    onCreateQRCode() {
      // 生成报名二维码
      this.qrcodeStatus = true;
      this.qrcodeUrl = vaildStudentUrl() + `/#/queryStudentPer`;
    },
    formatProtocol(version) {
        let str = '（含课程）'
        if(version == 3) {
            str = '（含系统）'
        } else if(version == 4) {
            str = '（含云教练）'
        }
        return str
    },
    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,
        hasCourse: null,
        // isMake: null,
        hasPracticeCourse: null,
        operatingTag: null,
        serviceTag: null,
        teacherId: null,
      };
      this.getList();
    },
    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,
        operatingTag: searchForm.operatingTag ? searchForm.operatingTag : null,
        serviceTag: searchForm.serviceTag ? searchForm.serviceTag : null,
        teacherId: searchForm.teacherId ? searchForm.teacherId : 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 + ".xls"; //下载文件的名字
                  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\d{10}$/;
      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.subjectIdList),
                  phone: val,
                  date: res.data.birthdate,
                };
              }
            }
          }
        );
      }
    },
    submitAddStudent() {
      const studentForm = this.studentForm;
      // 效验  然后组数据提交
      this.$refs["studentForm"].validate((item) => {
        if (item) {
          let obj = {
            phone: studentForm.phone,
            username: studentForm.name,
            gender: studentForm.sex,
            realName: studentForm.parseName,
            birthdate: studentForm.date,
            organId: studentForm.organId,
            serviceTag: studentForm.serviceTag,
            operatingTag: studentForm.operatingTag,
            teacherId: studentForm.teacherId,
            isNewUser: studentForm.isNewUser,
            subjectIdList: studentForm.subjectIdList,
            carePackage: studentForm.carePackage,
            comeOnPackage: studentForm.comeOnPackage,
            cooperationOrganId:studentForm.school
          };
          registerStudent(obj).then((res) => {
            if (res.code == 200) {
              this.$message.success("添加成功");
              this.studentVisible = false;
              this.getList();
            }
          });
        }
      });
    },
    // 修改学生信息
    resetStudentSubmie() {
      const studentForm = this.studentForm;
      this.$refs["studentForm"].validate((item) => {
        if (item) {
          let obj = {
            phone: studentForm.phone,
            username: studentForm.name,
            gender: studentForm.sex,
            realName: studentForm.parseName,
            birthdate: studentForm.date,
            organId: studentForm.organId,
            id: this.active.userId,
            serviceTag: studentForm.serviceTag,
            operatingTag: studentForm.operatingTag,
            teacherId: studentForm.teacherId,
            isNewUser: studentForm.isNewUser,
            subjectIdList: studentForm.subjectIdList,
            carePackage: studentForm.carePackage,
            comeOnPackage: studentForm.comeOnPackage,
              cooperationOrganId:studentForm.school
          };
          updateStudent(obj).then((res) => {
            if (res.code == 200) {
              this.$message.success("修改成功");
              this.studentVisible = false;
              this.getList();
            }
          });
        }
      });
    },
    async getSubjectList() {
      await subjectListTree({
        delFlag: "NO",
        tenantId: 1,
        rows: 9999,
      }).then((res) => {
        let result = res.data;
        if (res.code == 200) {
          let tempArray = [];
          result.rows.forEach((item, index) => {
            let subject = [];
            item.subjects.forEach((s) => {
              subject.push({
                value: s.id,
                label: s.name,
              });
            });

            tempArray[index] = {
              label: item.name,
              options: subject,
            };
          });
          this.subjectList = tempArray;
        }
      });
    },
    async addStudent() {
      await this.getSubjectList();
      this.isNew = true;
      this.studentVisible = true;
      this.maskName = "新增学员";
    },
    async resetStudent(row) {
      let organId = row.organId;
      await this.getSubjectList();
      await this.changeStudentOrgan(row.organId);
      this.isNew = false;
      this.active = row;
      this.studentVisible = true;
      this.maskName = "修改学员";
      this.$nextTick(() => {
        this.studentForm = {
          phone: row.parentsPhone || null,
          name: row.username || null,
          sex: row.gender,
          parseName: row.realName || null,
          date: row.birthdate || null,
          organId: row.organId || null,
          serviceTag: row.serviceTag,
          operatingTag: row.operatingTag,
          teacherId: row.teacherId || null,
          isNewUser: row.isNewUser,
          subjectIdList: Number(row.subjectIdList) || null,
          carePackage: row.carePackage,
          comeOnPackage: row.comeOnPackage,
          school:row.cooperationOrganId
        };
        this.studentUpdatePackage = {
          carePackage: row.carePackage,
          comeOnPackage: row.comeOnPackage,
        };
      });
    },
    onMaskClose(formName) {
      this.$refs[formName].resetFields();
    },
    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();
            }
          });
        }
      });
    },
    async changeStudentOrgan(val) {
      this.studentForm.teacherId = null;
      this.studentForm.school=null;
      if (val) {
        await getTeacher({ organId: val }).then((res) => {
          if (res.code == 200) {
            this.maskTeacherList = res.data;
          }
        });
        queryByOrganId({ organId: val }).then((res) => {
          if (res.code == 200) {
            this.cooperationList = res.data;
          }
        });
      } else {
        this.maskTeacherList = [];
      }
    },
    async lookContracts(row) {
      await getLatest({ userId: row.userId }).then((res) => {
        if (res.code == 200) {
          if (res.data) {
            this.protocolVersions = res.data;
            this.protocolVisible = true;
          }
        }
      });
    },
    onDownloadProtocol(item) {
      window.location.href = item.url;
    },
  },
};
</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 {
  .multiple.el-select {
    width: 185px !important;
  }
}
</style>
