<template>
  <div class="app-container fixed-scroll-error">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="姓名：">
        <el-input v-model="queryParams.studentName" placeholder="请输入学生姓名" clearable
          @keyup.enter.native="handleQuery"></el-input>
      </el-form-item>
      <el-form-item label="性别：">
        <el-select v-model="queryParams.sex" placeholder="请输入学生性别">
          <el-option v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.label" :value="dict.value">
            {{ dict.label }}
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="班级：">
        <el-select v-model="queryParams.classValue" placeholder="请输入学生班级">
          <el-option v-for="dict in dict.type.Class" :key="dict.value" :label="dict.label" :value="dict.value">
            {{ dict.label }}
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="注册序号：">
        <el-input v-model="queryParams.schoolNo" placeholder="请输入学生注册序号" clearable
          @keyup.enter.native="handleQuery"></el-input>
      </el-form-item>
      <el-form-item label="学生状态：">
        <el-select v-model="queryParams.studentStatus" placeholder="学生状态">
          <el-option v-for="dict in dict.type.child_state" :key="dict.value" :label="dict.label" :value="dict.value">
            {{ dict.label }}
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="学生类型：">
        <el-select v-model="queryParams.studentType" placeholder="请选择学生类型">
          <el-option v-for="dict in dict.type.student_type" :key="dict.value" :label="dict.label" :value="dict.value">
            {{ dict.label }}
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <!--      <el-col :span="1.5">-->
      <!--        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"-->
      <!--                   v-hasPermi="['system:student:add']">新增-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:student:edit']">编辑
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" size="mini" plain icon="el-icon-view" :disabled="single" @click="handleView">查看
        </el-button>
      </el-col>
      <el-col :span="3">
        <el-select style=" position: absolute; right: 0px; " size="mini" v-model="queryParams.schoolYear"
          @change="handleQuery">
          <el-option v-for="item in yearList" :key="item.value" :value="item.value" :label="item.label"></el-option>
        </el-select>
      </el-col>
      <!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>-->
    </el-row>
    <el-table stripe v-loading="loading" width="100%" :cell-style="cellStyle" :data="studentList"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column fixed="left" key="avatar" align="center" prop="avatar" label="头像">
        <template slot-scope="scope">
          <ListImage :image-url="isEmptyAvatar(scope.row.avatar, scope.row.sex)"></ListImage>
        </template>
      </el-table-column>
      <el-table-column fixed="left" key="studentName" min-width="80" align="center" prop="studentName" label="姓名" />
      <el-table-column key="score" min-width="80" align="center" prop="score" label="积分" />
      <el-table-column key="grade" min-width="100px" align="center" prop="classAlias" label="班级" />
      <el-table-column key="sex" min-width="50px" align="center" prop="sex" label="性别">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex"></dict-tag>
        </template>
      </el-table-column>
      <el-table-column key="nation" width="100" align="center" prop="nation" label="民族" />
      <el-table-column key="nativePlace" min-width="100" header-align="center" align="center" prop="nativePlace"
        label="籍贯" show-overflow-tooltip></el-table-column>
      <el-table-column key="idCard" width="180" align="center" prop="idCard" label="身份证号" />
      <el-table-column key="stuTelephone" width="130" align="center" prop="stuTelephone" label="联系电话" />
      <el-table-column key="birthAddress" width="150" align="center" prop="birthAddress" label="出生地" />
      <el-table-column key="postalCode" width="150" align="center" prop="postalCode" label="邮政编码" />
      <el-table-column key="enrollmentYear" width="100" align="center" prop="enrollmentYear" label="级/届" />
      <el-table-column key="enrollmentTime" min-width="100" header-align="center" align="center" prop="enrollmentTime"
        label="入学时间" show-overflow-tooltip></el-table-column>
      <el-table-column key="platform" width="180" align="center" prop="platform" label="平台" />
      <el-table-column key="studentType" width="130" align="center" prop="studentType" label="学生类型">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.student_type" :value="scope.row.studentType"></dict-tag>
        </template>
      </el-table-column>
      <el-table-column key="provincialNumber" width="150" align="center" prop="provincialNumber" label="省学籍辅号" />
      <el-table-column key="nationalNumber" width="150" align="center" prop="nationalNumber" label="全国学籍号" />
      <el-table-column key="studentStatus" width="80" align="center" prop="studentStatus" label="学生状态">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.child_state" :value="scope.row.studentStatus"></dict-tag>
        </template>
      </el-table-column>
      <el-table-column width="80" align="center" prop="studentType" label="学生类型">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.student_type" :value="scope.row.studentType"></dict-tag>
        </template>
      </el-table-column>
      <el-table-column key="schoolNo" width="100" align="center" prop="schoolNo" label="注册序号" />
      <el-table-column key="registeredAddress" min-width="100" header-align="center" align="center"
        prop="registeredAddress" label="户口所在地" show-overflow-tooltip></el-table-column>
      <el-table-column key="registeredType" width="180" align="center" prop="registeredType" label="户口性质">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.regist_type" :value="scope.row.registeredType" />
        </template>
      </el-table-column>
      <el-table-column key="juniorSchool" width="130" align="center" prop="juniorSchool" label="初中学校" />
      <el-table-column key="region" width="150" align="center" prop="region" label="国家地区" />
      <el-table-column key="foreignLanguages" width="150" align="center" prop="foreignLanguages" label="外语语种" />
      <el-table-column key="appearance" width="150" align="center" prop="appearance" label="政治面貌">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.politics_tatus" :value="scope.row.appearance"></dict-tag>
        </template>
      </el-table-column>
      <el-table-column key="birthday" width="120" sortable align="center" prop="birthday" label="出生日期"></el-table-column>
      <el-table-column key="homeAddress" min-width="200" align="center" prop="homeAddress" label="家庭住址"
        show-overflow-tooltip>
        <template v-slot="scope">
          <span class="one-line-omit">
            {{ scope.row.homeAddress }}
          </span>
        </template>
      </el-table-column>
      <el-table-column key="bloodType" width="100" align="center" prop="bloodType" label="血型" />
      <el-table-column key="health" min-width="100" header-align="center" align="center" prop="health" label="健康状况"
        show-overflow-tooltip></el-table-column>
      <el-table-column key="otherRegions" width="180" align="center" prop="otherRegions" label="港澳台侨" />
      <el-table-column key="floatingPopulation" width="130" align="center" prop="floatingPopulation" label="流动人口状况" />
      <el-table-column key="onlyChild" width="150" align="center" prop="onlyChild" label="独生子女">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.only_child" :value="scope.row.onlyChild" />
        </template>
      </el-table-column>
      <el-table-column key="nature" width="150" align="center" prop="nature" label="性质">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.student_nature" :value="scope.row.nature"></dict-tag>
        </template>
      </el-table-column>
      <el-table-column key="support" width="150" align="center" prop="support" label="接收资助情况"></el-table-column>
      <el-table-column label="操作" align="center" min-width="240px" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)" v-hasPermi="['system:student:edit']">编辑
          </el-button>
          <!--          <el-button icon="el-icon-delete" size="mini" type="text" @click="handleDelete(scope.row)"-->
          <!--                     v-hasPermi="['system:student:remove']">删除-->
          <!--          </el-button>-->
          <el-button size="mini" type="text" @click="parentsEdit(scope.row)" v-hasPermi="['system:student:edit']">家长信息
          </el-button>
          <el-button size="mini" type="text" @click="award(scope.row)">嘉奖
          </el-button>
          <el-button size="mini" type="text" @click="discipline(scope.row)">违纪
          </el-button>
          <!-- <el-button size="mini" type="text" @click="moralScore(scope.row)" v-hasPermi="['system:student:edit']">学生积分
          </el-button> -->
          <!--          <el-dropdown size="mini" @command="command => handleCommand(command, scope.row)"-->
          <!--                       v-hasPermi="['system:user:resetPwd', 'system:user:edit']">-->
          <!--            <span class="el-dropdown-link"> <i class="el-icon-d-arrow-right el-icon&#45;&#45;right"></i>更多 </span>-->
          <!--            <el-dropdown-menu slot="dropdown">-->
          <!--              &lt;!&ndash;              <el-dropdown-item command="classEdit">班级编辑</el-dropdown-item>&ndash;&gt;-->
          <!--              <el-dropdown-item command="parentsEdit">家长编辑</el-dropdown-item>-->
          <!--              <el-dropdown-item command="moralScore">德育打分</el-dropdown-item>-->
          <!--            </el-dropdown-menu>-->
          <!--          </el-dropdown>-->
        </template>
      </el-table-column>
    </el-table>
    <ExPagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改学生对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px">
      <el-form ref="form" :model="form" label-width="114px" :rules="rules">
        <el-form-item prop="avatar" label-width="0" style="display: flex; justify-content: center;">
          <el-upload v-loading="uploadLoading" class="avatar-uploader" :disabled="isEdit" action="#" accept="image/*"
            :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
            :http-request="uploadImage">
            <img v-if="imageUrl" :src="imageUrl" style="width: 178px; height: 178px;" class="avatar" alt="" />
            <!--                   :preview-src-list="[imageUrl]"-->
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div slot="error">
            <img :src="isEmptyAvatar(imageUrl, form.sex)" style="width: 178px; height: 178px; border-radius: 50%">
          </div>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="姓名：" prop="studentName">
              <el-input placeholder="请输入姓名" :disabled="isEdit" v-model="form.studentName" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="身份证号：" prop="idCard">
              <el-input placeholder="请输入身份证号" :disabled="isEdit" v-model="form.idCard" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="性别：" prop="sex">
              <el-select v-model="form.sex" placeholder="请输入性别" style="width: 100%;" :disabled="isEdit">
                <el-option v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.label"
                  :value="dict.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="籍贯：" prop="nativePlace">
              <el-input :disabled="isEdit" placeholder="请输入籍贯" v-model="form.nativePlace"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="出生日期：" prop="birthday">
              <el-date-picker v-model="form.birthday" :disabled="isEdit" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择出生日期" style="width: 100%;"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!--              <el-input :disabled="isEdit" v-model="form.className" clearable></el-input>-->
            <el-form-item label="班级：" prop="classAlias">
              <el-input :disabled="isEdit" v-model="form.classAlias" placeholder="请选择班级" readonly @focus="selectClass"
                style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="学生状态：" prop="studentStatus">
              <el-select :disabled="isEdit" v-model="form.studentStatus" placeholder="请输入学生状态" style="width: 100%;">
                <el-option v-for="dict in dict.type.child_state" :key="dict.value" :label="dict.label"
                  :value="dict.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="学生类型：" prop="studentType">
              <el-select :disabled="isEdit" v-model="form.studentType" placeholder="请输入学生类型" style="width: 100%;">
                <el-option v-for="dict in dict.type.student_type" :key="dict.value" :label="dict.label"
                  :value="dict.value">{{ dict.label }}
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="注册序号：" prop="schoolNo">
              <el-input :disabled="isEdit" placeholder="请输入注册序号" v-model="form.schoolNo"></el-input>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="省学籍辅号：" prop="provincialNumber">
              <el-input :disabled="isEdit" placeholder="请输入省学籍辅号" v-model="form.provincialNumber"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="全国学籍号：" prop="nationalNumber">
              <el-input :disabled="isEdit" placeholder="请输入全国学籍号" v-model="form.nationalNumber"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="民族：" prop="nation">
              <el-select :disabled="isEdit" v-model="form.nation" placeholder="请选择民族" style="width: 100%">
                <el-option v-for="item in Nations" :key="item.label" :label="item.label" :value="item.label"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="联系电话：" prop="stuTelephone">
              <el-input :disabled="allowEdit" placeholder="请输入联系电话" v-model="form.stuTelephone"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="现住地址：" prop="homeAddress">
              <el-input :disabled="allowEdit" placeholder="请输入现住地址" v-model="form.homeAddress"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="通讯地址：" prop="postalAddress">
              <el-input :disabled="allowEdit" placeholder="请输入通讯地址" v-model="form.postalAddress"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="邮政编码：" prop="postalCode">
              <el-input :disabled="isEdit" placeholder="请输入邮政编码" v-model="form.postalCode"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="级/届：" prop="enrollmentYear">
              <el-date-picker style="width:100%" :disabled="isEdit" v-model="form.enrollmentYear" type="year"
                placeholder="选择入学年">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入学时间：" prop="enrollmentTime">
              <el-date-picker v-model="form.enrollmentTime" :disabled="isEdit" style="width: 100%" type="date"
                placeholder="选择入学时间">
              </el-date-picker>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="平台：" prop="platform">
              <el-input :disabled="isEdit" placeholder="请输入平台" v-model="form.platform"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="初中学校：" prop="juniorSchool">
              <el-input :disabled="isEdit" placeholder="请输入初中学校" v-model="form.juniorSchool"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="校园一卡通：" prop="oneCard">
              <el-input :disabled="isEdit" placeholder="请输入校园一卡通号码" v-model="form.oneCard" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row :gutter="20">


        </el-row> -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="出生地：" prop="birthAddress">
              <el-input :disabled="isEdit" placeholder="请输入出生地" v-model="form.birthAddress"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="户口所在地：" prop="registeredAddress">
              <el-input :disabled="isEdit" placeholder="请输入户口所在地" v-model="form.registeredAddress"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="户口性质：" prop="registeredType">
              <el-select :disabled="isEdit" v-model="form.registeredType" style="width: 100%" placeholder="请输入户口性质">
                <el-option v-for="dict in dict.type.regist_type" :key="dict.value" :label="dict.label"
                  :value="dict.value">
                </el-option>
              </el-select>
            </el-form-item>


          </el-col>

        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="国家地区：" prop="region">
              <el-input :disabled="isEdit" placeholder="请输入国家地区" v-model="form.region"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="外语语种：" prop="foreignLanguages">
              <el-input :disabled="isEdit" placeholder="请输入外语语种" v-model="form.foreignLanguages"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="政治面貌：" prop="appearance">
              <el-select :disabled="isEdit" v-model="form.appearance" style="width: 100%" placeholder="请选择政治面貌">
                <el-option v-for="dict in dict.type.politics_tatus" :key="dict.value" :label="dict.label"
                  :value="dict.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="血型：" prop="bloodType">
              <el-input :disabled="isEdit" placeholder="请输入血型" v-model="form.bloodType"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="健康状况：" prop="health">
              <el-input :disabled="isEdit" placeholder="请输入健康状况" v-model="form.health"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="港澳台侨：" prop="otherRegions">
              <el-input :disabled="isEdit" placeholder="请输入港澳台侨" v-model="form.otherRegions"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="流动人口状况：" prop="floatingPopulation">
              <el-input :disabled="isEdit" placeholder="请输入流动人口状况" v-model="form.floatingPopulation"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="独生子女：" prop="onlyChild">
              <el-select :disabled="isEdit" v-model="form.onlyChild" style="width: 100%" placeholder="请选择是否为独生子女">
                <el-option v-for="dict in dict.type.only_child" :key="dict.value" :label="dict.label" :value="dict.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="性质：" prop="nature">
              <el-select :disabled="isEdit" v-model="form.nature" placeholder="请选择学生性质" style="width: 100%;">
                <el-option v-for="dict in dict.type.student_nature" :key="dict.value" :label="dict.label"
                  :value="dict.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="积分：" prop="score">
              <el-input :disabled="isEdit" placeholder="请输入积分" v-model="form.score"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="接收资助状况：" prop="support">
              <el-input :disabled="isEdit" placeholder="请输入接收资助状况" v-model="form.support"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-show="!allowEdit" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">{{ allowEdit ? '退 出' : '取 消' }}</el-button>
      </div>
      <!--      <div slot="footer" class="dialog-footer">-->
      <!--        <el-button type="primary" @click="submitForm">确 定</el-button>-->
      <!--        <el-button @click="cancel">取 消</el-button>-->
      <!--      </div>-->
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!--<div class="el-upload__tip" slot="tip">-->
          <!--  <el-checkbox v-model="upload.updateSupport"/>-->
          <!--  是否更新已经存在的用户数据-->
          <!--</div>-->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 选择班级 -->
    <GradeClassSelect v-if="classOptions.open" :openSelect.sync="classOptions.open" :title="classOptions.title"
      @getClassList="classList" @setClassInfo="setClassInfo"></GradeClassSelect>
    <ExportTable :open-export.sync="exportOptions.open" :title="exportOptions.title" @export="exportFile"></ExportTable>
  </div>
</template>

<script>
import ClassSelect from '@/views/smartSchool/gradeWork/studentManage/components/classSelect'
import GradeClassSelect from "@/views/smartSchool/gradeWork/component/gradeClassSelect";
import {
  getClassList,
  listStudent,
  getStudent,
  delStudent,
  addStudent,
  updateStudent
} from '@/api/smartSchool/gradeWork/studentManage'
import { getToken } from '@/utils/auth'
import { CustomCellStyle } from '@/enums/customStyle'
import PicAvatar from '@/views/smartSchool/schoolManage/introduce/schoolInfo/profile/picAvatar'
import { uploadImage as commonUpload } from '@/api/common'
import { ExportType, Gender, Nations } from '@/enums/common'
import { checkIdcard } from '@/utils/utilLibrary/validate'
import { getYearList } from '@/utils/utilLibrary/getYearList'
import { getNewYear } from "@/api/smartSchool/gradeWork/classView";


export default {
  name: 'studentManage',
  components: { PicAvatar, GradeClassSelect },
  dicts: ['only_child', 'regist_type', 'sys_user_sex', 'Grade', 'Class', 'student_type', 'Whether_Delete', 'child_state', 'politics_tatus', 'student_nature'],
  data() {
    return {
      pev: process.env.VUE_APP_BASE_API,
      allowEdit: false,
      isEdit: false,
      // 民族
      Nations,
      //获取子组件传来的信息
      pic: [],
      // 隐藏与显示列信息
      columns: [
        { key: 0, label: `头像`, visible: true },
        { key: 1, label: `姓名`, visible: true },
        { key: 2, label: `性别`, visible: true },
        { key: 3, label: `出生日期`, visible: true },
        { key: 4, label: `民族`, visible: true },
        { key: 5, label: `家庭住址`, visible: true },
        { key: 6, label: `籍贯`, visible: true },
        { key: 7, label: `年级`, visible: true },
        { key: 8, label: `班级`, visible: true },
        { key: 9, label: `禁忌食物`, visible: true },
        { key: 10, label: `学年`, visible: true },
        { key: 11, label: `身份证号`, visible: true },
        { key: 12, label: `注册序号`, visible: true },
        { key: 13, label: `学生状态`, visible: true },
        { key: 14, label: `学生类型`, visible: true },
        { key: 15, label: `校园一卡通`, visible: true }
      ],
      // 限制选择日期不能超过今天
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        }
      },
      // 图片路径
      imageUrl: undefined,
      // 图片上传遮罩层
      uploadLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学生表格数据
      studentList: [],
      // 增加家长信息列表
      parentsList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 家长编辑对话框
      dialogVisibleForParents: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        studentName: undefined,
        studentStatus: '',
        sex: '',
        grade: '',
        classes: '',
        studentType: '',
        schoolNo: '',
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // studentName: [{required: true, message: '学生姓名不能为空', trigger: 'blur'}],
        // schoolNo: [{required: true, message: '注册序号不能为空', trigger: 'blur'}],
        // studentType: [{required: true, message: '学生类型不能为空', trigger: 'change'}],
        // studentStatus: [{required: true, message: '学生状态不能为空', trigger: 'change'}],
        // idCard: [{required: true, validator: checkIdcard, trigger: 'blur'}],
        // classAlias: [{required: true, message: '班级不能为空', trigger: 'change'}],
      },
      // 班级编辑表单
      classForm: {
        name: '',
        birthday: '',
        id: '',
        studentNo: ''
      },
      // 班级编辑添加表格
      classTable: [],
      //选中的从表数据
      checkedDetail: [],
      // 德育打分日期
      moralScoreDate: '',
      // 德育打分列表
      moralTableList: [
        {
          description: '擦黑板',
          score: 3
        }
      ],
      // 学生导入参数
      upload: {
        // 是否显示弹出层（学生导入）
        open: false,
        // 弹出层标题（学生导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的学生数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/school/student/importData'
      },
      //
      tableKey: Math.random(),
      // 自定义列表单元格样式
      cellStyle: CustomCellStyle,
      // 选择班级对话框
      classOptions: {
        open: false,
        title: '选择班级'
      },
      // 导出选项
      exportOptions: {
        title: '选择导出类别',
        open: false
      },
      // 导出
      exportType: '',
      // 年份列表数据
      yearList: []
    }
  },
  computed: {
    resolveName() {
      return form => {
        // if (form.id) {
        const result = []
        const grade = this.dict.type.Grade.find(item => item.value == form.grade)
        const classes = this.dict.type.Class.find(item => item.value == form.classes)
        // result.push(form.schoolYear);
        grade && result.push(grade.label);
        classes && result.push(classes.label);
        form.gradeAlias = result.join('-');
        // }
        return form.gradeAlias;
      }
    },
    resolveAvatar() {
      return (url, sex) => {
        return this.isEmptyAvatar(url, sex);
      }
    }
  },
  watch: {
    // elementUi时间日期控件传值不能为Number类型，必须为String。
    'form.schoolYear'(val) {
      this.form.schoolYear = '' + val
    },
    pic: {
      handler(newValue, oldValue) {
        this.isUploadPic = newValue[3]
      }
    },
  },
  created() {
    // this.WebSocketTest()
    this.newYear()
    // this.getList()
    this.yearList = getYearList()
  },
  // activated() {
  //   this.WebSocketTest()
  // },
  methods: {
    WebSocketTest() {
      let that = this
      // wss://127.0.0.1:8848/webSocket/1?Authorization=Bearer%20eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6ImI4ZDgxNGM3LWVkZTAtNGIyOC1iMjA5LTM4OTFkMGE5ODI3NSJ9.EeNyWK19AHKmEzXouYf-k8BZO987knIgX5_Uq0nzSGDSReWFy0x-ROCSWwvlL1a6mOE2n9G3X7GiFsvsSCbRPA
      if ("WebSocket" in window) {
        // let url = `${this.pev}/webSocket/${this.$store.state.user.userId}`
        let Authorization = "Bearer " + getToken()
        //本地测试
        //let url = `ws://127.0.0.1:8848/ws/webSocket/${this.$store.state.user.userId}`
        //部署时需改成对应前端监听端口，以代理到对应后端地址，测试
        //let url = `ws://47.105.176.202:8135/ws/webSocket/${this.$store.state.user.userId}`
        //试运行
        let url = `ws://10.20.100.201:57321/ws/webSocket/${this.$store.state.user.userId}`
        let ws = new WebSocket(url)
        ws.onopen = function () {
          ws.send("发送数据")
        }
        ws.onmessage = function (evt) {
          let received_msg = evt.data
          received_msg = JSON.parse(received_msg)
          if (received_msg.users[0] && received_msg.users[0].grade === '1') {
            that.allowEdit = false
          } else if (received_msg.users[0] && received_msg.users[0].grade === '0') {
            that.allowEdit = true
          }
        }

        ws.onclose = function () {

        }
      } else {
        // 浏览器不支持 WebSocket
        // alert("您的浏览器不支持 WebSocket!")
      }
    },


    newYear() {
      getNewYear().then((res) => {
        this.queryParams.schoolYear = res.schoolYear
        // this.handleYearChange(res.schoolYear)
        this.getList()
      })
    },
    /** 查询学生列表 */
    getList() {
      this.loading = true
      listStudent(this.queryParams).then(response => {
        // console.log(response)
        this.studentList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        gradeId: '',
        oneCard: '',
        studentType: '',
        studentStatus: '',
        tabooFood: '',
        schoolNo: '',
        idCard: '',
        classes: '',
        grade: '',
        schoolYear: '',
        nativePlace: '',
        homeAddress: '',
        nation: '',
        birthday: '',
        sex: Gender.MALE,
        studentName: '',
        avatar: ''
      }
      this.imageUrl = ''
      this.resetForm('form')
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        studentName: undefined,
        studentStatus: '',
        sex: '',
        grade: '',
        classValue: '',
        studentType: '',
        schoolNo: '',
        // schoolYear: new Date().getFullYear()
      }
      // this.queryParams.pageNum = 1
      this.newYear()
      // this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 获取学生头像
    getStudentInfoPic(val) {
      this.pic = val
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.isEdit = false,
        this.open = true;
      this.title = '添加学生信息';
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.WebSocketTest()
      this.isEdit = true;
      const id = row.id || this.ids;
      // 获取学生个人信息
      getStudent(id).then(response => {
        this.form = response.data;
        this.imageUrl = this.isEmptyAvatar(this.form.avatar, this.form.sex);
        this.open = true;
        this.title = '修改学生信息';
      })
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateStudent(this.form).then(({ code }) => {
              if (code == 200) {
                this.$modal.msgSuccess('修改成功')
                this.open = false
                this.getList()
              }
            }).catch(() => {
              this.$modal.msgError("修改失败");
            }
            )
          } else {
            addStudent(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            }).catch(() => {
              this.$modal.msgError("新增失败");
            }
            )
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id || this.ids
      this.$modal
        .confirm('是否确认删除选中的数据项？')
        .then(function () {
          return delStudent(id)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {
        })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = '学生导入'
      this.upload.open = true
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', { dangerouslyUseHTMLString: true })
      this.getList()
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },
    /** 导出按钮操作 */
    handleExport() {
      // 导出选中，导出全部，根据查询条件导出
      this.exportOptions.open = true
    },
    /** 导出 */
    exportFile(callback) {
      const ids = this.ids
      const options = [
        { type: ExportType.TOTAL, path: '/school/student/export', params: {} },
        { type: ExportType.SELECT, path: '/school/student/export/' + ids, params: {} },
        { type: ExportType.QUERY, path: '/school/student/export', params: this.queryParams }
      ]
      callback(options, `学生信息${new Date().getTime()}.xlsx`)
    },

    /** 关闭 */
    closeExport() {
      this.exportOptions.open = false
    },
    // 下载学生模板
    importTemplate() {
      this.download('/school/student/importTemplate', {}, `student_template_${Date.now()}.xlsx`)
    },
    // 移除图片
    handleRemove() {
      this.imageUrl = undefined
    },
    // 上传成功回调
    handleAvatarSuccess(res, file) {
      this.imageUrl = res.data.url
      this.commonUpload(file)
    },
    // 上传前格式和图片大小限制
    beforeAvatarUpload(file) {
      const type = file.type === 'image/jpeg' || 'image/jpg' || 'image/webp' || 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!type) {
        this.$message.error('图片格式不正确!(只能包含jpg，png，webp，JPEG)')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return type && isLt2M
    },

    // 上传图片
    uploadImage(file) {
      const fileData = file.file
      const formData = new FormData()
      formData.append('file', fileData)
      this.uploadLoading = true
      commonUpload(formData)
        .then(response => {
          this.uploadLoading = false
          this.$modal.msgSuccess('上传成功')
          this.imageUrl = this.pev + response.url
          this.form.avatar = response.url
        })
        .catch(error => {
          this.uploadLoading = false
        })
    },

    // 班级编辑
    // classEdit(row) {
    //   const id = row.id
    //   this.$router.push({
    //     path: '/studentmanage/stuclass',
    //     query: {studentId: row.id}
    //   })
    // },
    // 家长编辑
    parentsEdit(row) {
      const id = row.id
      this.$router.push({
        path: '/gradeWork/studentManage/parentInfo',
        query: { studentId: row.id }
      })
    },
    // // 学生积分
    // moralScore(row) {
    //   this.$router.push({
    //     path: '/gradeWork/studentmanage/score',
    //     query: {
    //       id: row.id,
    //       name: row.studentName,
    //       idCard: row.idCard,
    //       schoolNo: row.schoolNo,
    //       schoolYear: this.queryParams.schoolYear
    //     }
    //   })
    // },
    // 学生嘉奖
    award(row) {
      this.$router.push({
        path: '/classAdviser/studentManage/studentCommendation',
        query: {
          // id: row.id,
          // name: row.studentName,
          // idCard: row.idCard,
          // schoolNo: row.schoolNo,
          // schoolYear: this.queryParams.schoolYear
        }
      })

    },
    //违纪
    discipline(row) {
      this.$router.push({
        path: '/classAdviser/studentManage/discipline',
        query: {
          // id: row.id,
          // name: row.studentName,
          // idCard: row.idCard,
          // schoolNo: row.schoolNo,
          // schoolYear: this.queryParams.schoolYear
        }
      })
    },
    // /** 更多下拉菜单 */
    // handleCommand(command, row) {
    //   this[command].apply(undefined, [row])
    // },

    /** 选择班级(打开对话框) */
    selectClass() {
      this.classOptions.open = true
    },
    /** 获取班级信息列表 */
    classList(queryForm, callback) {
      getClassList(queryForm)
        .then(response => {
          callback(response.rows, response.total)
        })
        .catch(error => {
          callback([], 0)
        })
    },

    /** 查看按钮操作 */
    handleView(row) {
      this.reset();
      this.isEdit = true;
      this.allowEdit = true;
      const id = row.id || this.ids;
      // 获取学生个人信息
      getStudent(id).then(response => {
        this.form = response.data;
        this.imageUrl = this.isEmptyAvatar(this.form.avatar, this.form.sex);
        this.formDisabled = true;
        this.open = true;
        this.title = '学生信息查看';
        // 如果图片为空
      })
    },

    /** 设置班级信息 */
    setClassInfo(item) {
      // this.$set(this.form, 'schoolYear', item.schoolYear)
      // this.$set(this.form, 'grade', item.gradeValue)
      // this.$set(this.form, 'classes', item.classValue)
      this.$set(this.form, 'classId', item.id)
      // this.$set(this.form, 'className', item.className)
      this.$set(this.form, 'classAlias', item.classAlias)
    },

    /** 判断学生头像是否为空 */
    isEmptyAvatar(imageUrl, sex) {
      if (!imageUrl) {
        let url = null;
        if (Gender.MALE === sex) {
          url = require('@/assets/images/boy.png');
        } else {
          url = require('@/assets/images/girl.png');
        }
        return url;
      } else {
        return this.pev + imageUrl;
      }
    }
  }
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<!--<style lang="scss" scoped>-->
<!--.custom-image-header {-->
<!--  div {-->
<!--    border: 1px dashed #ccc;-->
<!--    transform: none !important;-->
<!--  }-->
<!--}-->
<!--</style>-->
