<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input v-model="deptName" placeholder="请输入部门名称" clearable size="small" prefix-icon="el-icon-search"
            style="margin-bottom: 20px" />
        </div>
        <div class="head-container">
          <el-tree v-if="deptOptions.length > 0" :data="deptOptions" :props="defaultProps" :expand-on-click-node="false"
            :filter-node-method="filterNode" ref="tree" :default-expanded-keys="[]" highlight-current
            @node-click="handleNodeClick"></el-tree>

        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" label-width="90px" :inline="true" v-show="showSearch">
          <el-form-item label="姓名" clearable prop="teacherName">
            <el-input v-model="queryParams.teacherName" placeholder="请输入姓名" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="用户状态" label-width="70px" prop="status">
            <el-select v-model="queryParams.status" style="width: 100%" @keyup.enter.native="handleQuery"
              placeholder="请选择状态">
              <el-option v-for="dict in dict.type.user_status" :key="dict.value" :label="dict.label"
                :value="dict.value"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="职工类型" prop="employeeType">
            <el-select v-model="queryParams.employeeType" placeholder="请选择职工类型" clearable>
              <el-option v-for="dict in dict.type.employee_type" :key="dict.value" :label="dict.label"
                :value="dict.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="电话" clearable prop="teacherTel">
            <el-input v-model="queryParams.teacherTel" placeholder="请输入电话" clearable @keyup.enter.native="handleQuery" />
          </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="['teacherManage:inform:add']">新增
            </el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="info" plain icon="el-icon-search" size="mini" :disabled="single" @click="handleDetail">详情
            </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="['teacherManage:inform:edit']">修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                       v-hasPermi="['teacherManage:inform:remove']">删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport">导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                       v-hasPermi="['teacherManage:inform:export']">导出
            </el-button>
          </el-col> -->
          <!--          <right-toolbar-->
          <!--            :showSearch.sync="showSearch"-->
          <!--            @queryTable="getList"-->
          <!--            :columns="columns"-->
          <!--          ></right-toolbar>-->
        </el-row>

        <el-table v-loading="loading" :data="informList" :cell-style="cellStyle"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" :selectable="isSelected" />
          <el-table-column label="头像" align="center" prop="picUrl">
            <template slot-scope="scope">
              <ListImage :image-url="peV + scope.row.avatar"></ListImage>
            </template>
          </el-table-column>
          <el-table-column label="姓名" align="center" prop="teacherName" min-width="150">
            <template slot-scope="scope">
              <el-link type="primary" @click="handleDetail(scope.row)" :underline="false">{{ scope.row.teacherName }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column label="性别" align="center" prop="sex">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex" />
            </template>
          </el-table-column>
          <el-table-column label="工作编号" width="110px" align="center" prop="teacherCode" />
          <el-table-column label="部门" min-width="130px" align="center" prop="deptName" />
          <el-table-column label="手机号话" width="120px" align="center" prop="teacherTel" />
          <el-table-column label="职工类型" align="center" prop="employeeType">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.employee_type" :value="scope.row.employeeType" />
            </template>
          </el-table-column>
          <el-table-column label="状态" min-width="70px" align="center">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.status" :active-value="'0'" :inactive-value="'1'" active-color="#13ce66"
                @change="(res) => { switchChange(scope.row, res) }" inactive-color="#ff4949">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="签名" width="100px" align="center" prop="sign">
            <template slot-scope="scope">
              <ListImage :image-url="peV + scope.row.sign"></ListImage>
            </template>

          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="170" fixed="right">
            <template slot-scope="scope">
              <el-button v-if="!(scope.row.id == '1')" size="mini" type="text" icon="el-icon-edit"
                @click="handleUpdate(scope.row)" v-hasPermi="['teacherManage:inform:edit']">修改
              </el-button>
              <el-button v-if="!(scope.row.id == '1')" size="mini" type="text" icon="el-icon-delete"
                @click="handleDelete(scope.row)" v-hasPermi="['teacherManage:inform:remove']">删除
              </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--right"></i>更多
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="handleHonor">
                    荣誉编辑
                  </el-dropdown-item>
                  <el-dropdown-item command="handleResume">
                    履历编辑
                  </el-dropdown-item>
                  <el-dropdown-item command="handleResetPwd">
                    重置密码
                  </el-dropdown-item>
                  <el-dropdown-item command="handleAuthRole">
                    分配角色
                  </el-dropdown-item>
                  <!--<el-dropdown-item command="handleClassView">任课班级</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-col>
    </el-row>

    <!-- 导入 -->
    <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>

    <!-- 导出对话框 -->
    <ExportTable :open-export.sync="exportOptions.open" :title="exportOptions.title" @export="exportFile"></ExportTable>
    <!-- 添加或修改学校老师对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form size="small" ref="form" :model="form" :rules="rules" :disabled="isDisabled" label-width="120px">
        <el-row :gutter="40">
          <el-col :span="12" style="text-align: center;">
            <el-form-item prop="picUrl" label-width="0px">
              <template slot-scope="scope">
                <el-upload style=" margin: auto" v-loading="photoUploadLoading" class="avatar-uploader" action="#"
                  accept="image/*" :show-file-list="false" :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload" :http-request="(res) => uploadImage(res, 'photo')">
                  <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </template>
            </el-form-item>
            <div style="width:50px; height: 20px;    margin:auto;"><b>照片</b></div>
            <br />
            <el-form-item label="姓名" prop="teacherName">
              <el-input v-model="form.teacherName" placeholder="请输入姓名" />
            </el-form-item>
            <el-form-item label="手机号码" prop="teacherTel">
              <el-input v-model="form.teacherTel" placeholder="请输入老师电话" />
            </el-form-item>
            <el-form-item label="身份证号" prop="idCard">
              <el-input v-model.trim="form.idCard" placeholder="请输入身份证号" />
            </el-form-item>
            <el-form-item label="性别" prop="sex">
              <el-select v-model="form.sex" style="width: 100%" placeholder="请选择性别">
                <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-form-item label="职工类型" prop="employeeType">
              <el-select v-model="form.employeeType" style="width: 100%" placeholder="请选择职工类型">
                <el-option v-for="dict in dict.type.employee_type" :key="dict.value" :label="dict.label"
                  :value="dict.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="民族" prop="nation">
              <el-select v-model="form.nation" style="width: 100%" placeholder="请选择民族">
                <el-option v-for="item in Nations" :key="item.label" :label="item.label" :value="item.label"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="生日" prop="birthday">
              <el-date-picker clearable v-model="form.birthday" type="date" style="width: 100%" value-format="yyyy-MM-dd"
                placeholder="请选择生日"></el-date-picker>
            </el-form-item>

            <el-form-item label="岗位" prop="postId">
              <el-select v-model="form.postIds" multiple placeholder="请选择岗位" style="width: 100%">
                <el-option v-for="item in postOptions" :key="item.postId" :label="item.postName"
                  :value="item.postId"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="任职部门" prop="deptIds">
              <treeselect :disabled="isDisabled" v-model="form.deptIds" :options="deptOptions" :show-count="true"
                :defaultExpandLevel="2" placeholder="请选择主部门" @change="handleSelectionChange" multiple :max="8" />
              <!-- 添加 multiple 和 max 属性 -->
            </el-form-item>



          </el-col>
          <el-col :span="12" style="text-align: center">
            <el-form-item prop="picUrl" label-width="0px">
              <template slot-scope="scope">
                <el-upload style="margin: auto" v-loading="signUploadLoading" class="avatar-uploader" action="#"
                  accept="image/*" :show-file-list="false" :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload" :http-request="(res) => uploadImage(res, 'sign')">
                  <img v-if="signUrl" :src="signUrl" class="avatar" />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </template>
            </el-form-item>
            <div style="width:50px; height: 20px;margin:auto;"><b>签名</b></div>
            <br />
            <el-form-item label="主部门" prop="deptId">
              <treeselect :disabled="isDisabled" v-model="form.deptId" :options="deptOptions" :show-count="true"
                :defaultExpandLevel="2" placeholder="请选择主部门" />
            </el-form-item>
            <!--            :placeholder="isDisabled ? '' : '请选择归属部门'"-->
            <el-form-item label="密码" v-if="!form.id" prop="password">
              <el-input v-model="form.password" placeholder="请输入密码" class="pwd" type="text" autocomplete="new-password"
                maxlength="20" />
            </el-form-item>
            <el-form-item label="工作编号" prop="teacherCode">
              <el-input v-model="form.teacherCode" placeholder="请输入工作编号" />
            </el-form-item>
            <el-form-item label="设备工号" prop="deviceNum">
              <el-input v-model="form.deviceNum" placeholder="请输入设备工号" style="width: 100%"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" />
            </el-form-item>
            <el-form-item label="学历" prop="education">
              <el-select v-model="form.education" style="width: 100%" placeholder="请选择学历">
                <el-option v-for="dict in dict.type.education" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" style="width: 100%" placeholder="请选择用户状态">
                <el-option v-for="dict in dict.type.user_status" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="角色" prop="roleId">
              <el-select v-model="form.roleIds" multiple placeholder="请选择角色" style="width: 100%">
                <el-option v-for="item in roleOptions" :key="item.roleId" :label="item.roleName"
                  :value="item.roleId"></el-option>
              </el-select>
            </el-form-item>

          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="家庭住址" prop="homeAddress">
            <el-input type="textarea" v-model="form.homeAddress" placeholder="请输入家庭住址" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" v-model="form.remark" placeholder="请输入备注" />
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-show="!isDisabled" type="primary" @click="submitForm">确 定
        </el-button>
        <el-button @click="cancel">{{
          isDisabled ? "退 出" : "取 消"
        }}
        </el-button>
      </div>
    </el-dialog>
    <!-- 分配角色 -->
    <el-dialog :title="title" :visible.sync="assignRolesopen" width="400px" append-to-body>
      <el-form label-width="80px">
        <el-form-item label="姓名">
          <el-input v-model="teacherName" style="width: 180px"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="authRole" placeholder="请选择角色" multiple style="width: 180px">
            <el-option v-for="item in roleOptions" :key="item.roleId" :label="item.roleName"
              :value="item.roleId"></el-option>
          </el-select>
        </el-form-item>


      </el-form>
      <div style="margin: 20px 0 -10px 180px">
        <el-button @click="close" style="margin: 0 10px 0 0">取消</el-button>
        <el-button @click="submitAssignRoles" style="margin: 0 0 0 10px" type="primary">确定
        </el-button>
      </div>
    </el-dialog>
    <!-- 重置密码 -->
    <el-dialog :title="title" :visible.sync="resetPasswordopen" width="400px" append-to-body>
      <el-form lable-with="100px">
        <el-form-item label="姓名">
          <el-input v-model="teacherName" style="width: 60%"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="password" show-password style="width: 60%" placeholder="请输入原密码"></el-input>
        </el-form-item>
      </el-form>
      <div style="margin: 20px 0 -10px 180px">
        <el-button @click="close" style="margin: 0 10px 0 0">取消</el-button>
        <el-button @click="submitReset" style="margin: 0 0 0 10px" type="primary">确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listInform,
  getInform,
  delInform,
  addInform,
  updateInform,
  sendResetPassword,
  submitRoles,
} from "@/api/smartSchool/teacherManage/teacherInforManage";
import { listResume } from "@/api/smartSchool/teacherManage/resume";
import { listTeacherAward } from "@/api/smartSchool/teacherManage/teacherAward";
import { CustomCellStyle } from "@/enums/customStyle";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { ExportType, Gender, Nations } from "@/enums/common";
import { checkIdcard } from "@/utils/utilLibrary/validate";
import { getToken } from "@/utils/auth";
import { uploadImage as commonUpload, signUpload } from "@/api/common";
import { resetUserPwd } from "@/api/system/user";
import { statusChange } from "../../../../api/smartSchool/teacherManage/teacherInforManage";

export default {
  name: "Inform",
  dicts: ["education", "sys_user_sex", "honor", "user_status", "employee_type"],
  components: {
    Treeselect,
  },
  data() {
    return {

      peV: process.env.VUE_APP_BASE_API,
      // 民族
      Nations,
      honorQueryAdd: {},
      isDisabled: false, // 根据需要设置是否禁用
      deptOptions: [
        // 选项数据
      ],
      honorTitle: undefined,
      honorQuery: {},
      resumeTitle: undefined,
      teacherId: undefined,
      resumeQuery: {},
      // 图片路径
      imageUrl: undefined,
      signUrl: undefined,
      // 遮罩层
      loading: true,
      resumeListLoading: false,
      honorListLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // resume选中数组
      resumeIds: [],
      // 非单个禁用
      resumeSingle: true,
      // 非多个禁用
      resumeMultiple: true,
      // honor选中数组
      honorIds: [],
      // 非单个禁用
      honorSingle: true,
      // 非多个禁用
      honorMultiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学校老师表格数据
      informList: [],
      // 简历数据表格
      resumeList: [],
      honorList: [],
      // 弹出层标题
      title: "",
      // 用户姓名
      teacherName: "",
      // 用户密码
      password: "",
      // 用户id
      userId: "",
      // 用户角色
      authRole: [],

      // 是否显示弹出层
      open: false,
      assignRolesopen: false,
      resetPasswordopen: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        teacherName: null,
        teacherTel: null,
        teacherCode: null,
        idCard: null,
        homeAddress: null,
        nation: null,
        picUrl: null,
        birthday: null,
        education: null,
        status: null,
        deptId: null,
        employeeType: null,
      },
      // 表单参数
      form: {
        deptIds: [],
      },
      // 列信息
      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 },
      ],
      // 表单校验
      rules: {
        teacherName: [
          { required: true, message: "老师名称不能为空", trigger: "blur" },
        ],
        teacherTel: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
        password: [{ required: true, message: "登录密码不能为空", trigger: "blur" },],
        // teacherCode: [{ required: true, message: "工作编号不能为空", trigger: "blur" },
        // { message: "工作编号格式不正确", trigger: "blur", pattern: /[0-9]\d*/ },
        // ],
        // idCard: [{ required: true, validator: checkIdcard, trigger: "blur" }],
        deptId: [{ required: true, message: "归属部门不能为空", trigger: "change" }],
        // employeeType: [{ required: true, message: "职工类型不能为空", trigger: "change" }],
        // deviceNum: [{ required: true, message: "设备工号不能为空", trigger: "change" }],
        // sex: [{ required: true, message: "性别不能为空", trigger: "change" }],
      },

      // 自定义列表单元格样式
      cellStyle: CustomCellStyle,
      // 部门列表数据
      deptOptions: [],
      // 岗位列表
      postOptions: [],
      // 角色列表
      roleOptions: [],
      // 默认密码
      initPassword: undefined,
      //导入
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/school/teacher/importData",
      },
      // 导出选项
      exportOptions: {
        title: "选择导出类别",
        open: false,
      },
      // 上传状态
      photoUploadLoading: false,
      signUploadLoading: false,
      defaultProps: {
        children: "children",
        label: "label",
      },
      deptName: "",
      // 是否禁用表单
      isDisabled: false,
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
    'form.deptIds'(newVal) {
      if (newVal.length > 8) {
        // If the selection exceeds the limit, remove the last item
        this.form.deptIds.pop();
      }
    }
  },
  created() {
    this.getList();
    this.getDeptTree();
    // this.getConfigKey('sys.user.initPassword').then(response => {
    //   this.initPassword = response.msg
    // })
  },

  methods: {
    handleSelectionChange(selectedItems) {
      if (selectedItems.length > 8) {
        // 用户选择的项数超过了最大限制，您可以在此处进行处理，例如取消选择最后一个项
        this.form.deptIds.pop();
      }
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.handleQuery();


    },

    /** 查询学校老师列表 */
    getList() {
      this.loading = true;
      listInform(this.queryParams).then((response) => {
        this.informList = response.rows;

        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        teacherName: null,
        // userName: null,
        teacherTel: null,
        // phonenumber: null,
        teacherCode: null,
        idCard: null,
        homeAddress: null,
        nation: null,
        picUrl: null,
        birthday: null,
        education: null,
        sex: null,
        postIds: null,
        roleIds: null,
        deptId: null,
        password: null,
      };
      this.imageUrl = "";
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.throttle(() => {
        this.queryParams.pageNum = 1;
        this.getList();
      });
    },
    getResumelist() {
      this.resumeListLoading = true;
      listResume({ teacherId: this.teacherId }).then((res) => {
        if (res.code == 200) {
          this.resumeList = res.rows;
          this.resumeListLoading = false;
        } else {
          this.$message.error("数据请求失败");
          this.resumeListLoading = false;
        }
      });
    },
    getHonorlist() {
      this.honorListLoading = true;
      listTeacherAward({ teacherId: this.teacherId }).then((res) => {
        if (res.code == 200) {
          this.honorList = res.rows;
          this.honorListLoading = false;
        } else {
          this.$message.error("数据请求失败");
          this.honorListLoading = false;
        }
      });
    },
    handleResume(row) {
      this.$router.push({
        path: "/teacherManage/resume",
        query: {
          teacherId: row.id,
        },
      });
    },
    handleHonor(row) {
      // 进入下一个页面
      this.$router.push({
        path: "/teacherManage/awardDetails",
        query: {
          teacherId: row.id,
        },
      });
    },
    handleClassView(row) {
      this.$router.push({
        path: "/teachManage/classView",
        query: {
          teacherId: row.id,
        },
      });
    },

    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.teacherName + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: "用户密码长度必须介于 5 和 20 之间"
      }).then(({ value }) => {
        resetUserPwd(row.userId, value).then(response => {
          this.$modal.msgSuccess("修改成功，新密码是：" + value);
        });
      }).catch(() => {
      });
    },
    /** 分配角色操作 */
    handleAuthRole: function (row) {
      // const userId = row.userId;
      this.$router.push({
        path: "/teacherInforManage/authRole",
        query: {
          userId: row.userId
        }
      });
    },

    //确认分配角色
    submitAssignRoles() {
      console.log(this.authRole);
      let query = {};
      query.id = this.userId;
      query.authRole = this.authRole;
      submitRoles(query).then((res) => {
        this.assignRolesopen = false;
        this.$message({
          type: "success",
          message: `分配角色成功`,
        });
      });
    },
    // 关闭对话框
    close() {
      this.assignRolesopen = false;
      this.resetPasswordopen = false;
    },
    //确认重置密码
    submitReset() {
      let query = {};
      query.userId = this.userId;
      query.password = this.password;
      sendResetPassword(query).then((res) => {
        this.resetPasswordopen = false;
        this.$message({
          type: "info",
          message: `重置密码成功`,
        });
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.isDisabled = false;
      this.reset();
      this.signUrl = "",
        this.imageUrl = "",
        this.open = true;
      this.title = "添加教职工信息";
      this.getPostAndRoleList();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getPostAndRoleList();
      const id = row.id || this.ids;
      this.$modal.loading("正在加载数据，请稍等...");
      getInform(id)
        .then((response) => {
          this.$modal.closeLoading();
          this.form = response.data;
          this.imageUrl = this.peV + this.form.picUrl;
          this.signUrl = this.peV + this.form.sign;
          this.open = true;
          this.isDisabled = false;
          this.title = "修改教职工信息";
        })
        .catch((error) => {
          this.$modal.closeLoading();
        });
    },
    /** 查看详情 */
    handleDetail(row) {
      this.reset();
      this.getPostAndRoleList();
      const id = row.id || this.ids;
      this.$modal.loading("正在加载数据，请稍等...");
      getInform(id)
        .then((response) => {
          this.$modal.closeLoading();
          this.form = response.data;
          this.imageUrl = this.form.picUrl;
          this.open = true;
          this.isDisabled = true;
          this.title = "查看教职工信息";
        })
        .catch((error) => {
          this.$modal.closeLoading();
        });
    },
    // 上传成功回调
    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, type) {
      const fileData = file.file;
      const formData = new FormData();
      formData.append("file", fileData);
      if (type == 'photo') {
        this.photoUploadLoading = true;
        commonUpload(formData).then((response) => {
          console.log(response, 1147)
          this.photoUploadLoading = false;
          this.$modal.msgSuccess("上传成功");
          this.imageUrl = process.env.VUE_APP_BASE_API + response.url;
          this.form.avatar = response.url;
        }).catch((error) => {
          this.photoUploadLoading = false;
        });
      } else {
        this.signUploadLoading = true;
        signUpload(formData).then((response) => {
          this.signUploadLoading = false;
          this.$modal.msgSuccess("上传成功");
          this.signUrl = process.env.VUE_APP_BASE_API + response.url;
          this.form.sign = response.url;
        }).catch((error) => {
          this.signUploadLoading = false;
        });
      }

    },

    /** 提交按钮 */
    submitForm() {
      if (!this.form.picUrl) {
        if (this.form.sex === Gender.FEMALE) {
          this.form.picUrl =
            "https://eos-wuxi-1.cmecloud.cn/dy-pro/image/2022/08/09/b076ed42bfca4a8cae062dfffd5f3618.jpg";
        } else {
          this.form.picUrl =
            "https://eos-wuxi-1.cmecloud.cn/dy-pro/image/2022/08/09/8a6c1334494d418d8a53cc7bf5abd668.jpg";
        }
      }
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateInform(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInform(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm(
          `是否确认删除选中的${Object.hasOwnProperty.call(ids, "length") ? ids.length : 1
          }条数据？`
        )
        .then(() => {
          this.$modal.loading("正在删除数据，请稍等...");
          return delInform(ids);
        })
        .then(() => {
          this.$modal.closeLoading();
          this.$modal.msgSuccess("删除成功");
          this.getList();
        })
        .catch(() => {
          this.$modal.closeLoading();
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      // 导出选中，导出全部，根据查询条件导出
      this.exportOptions.open = true;
      // this.$confirm(`是否确认导出${ !!this.ids.length ? this.ids.length + '条' : '所有' }数据？`, '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).then(() => {
      //   if (this.ids.length) {
      //     this.download('/school/teacher/export/' + this.ids, {
      //       ...this.queryParams
      //     }, `教师信息.xlsx`)
      //   } else {
      //     this.download('/school/teacher/export', {
      //       ...this.queryParams
      //     }, `教师信息.xlsx`)
      //   }
      //
      // }).catch(() => {
      //
      // });
    },

    /** 导入按钮 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    dateFormat(row, column, cellValue, index) {
      const daterc = row[column.property];
      if (daterc) {
        if (daterc.indexOf("T") === -1) return daterc;
        const arr = daterc.split("T");
        const d = arr[0];
        const darr = d.split("-");
        const t = arr[1];
        const tarr = t.split(".000");
        const marr = tarr[0].split(":");
        const dd = darr[0] + "-" + darr[1] + "-" + darr[2];
        return dd;
      }
    },
    /** 更多下拉菜单 */
    // handleCommand(command, row) {
    //   this[command].apply(undefined, [row]);
    // },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleHonor":
          this.handleHonor(row)
          break;
        case "handleResume":
          this.handleResume(row)
          break;
        case "handleResetPwd":
          this.handleResetPwd(row);
          break;
        case "handleAuthRole":
          this.handleAuthRole(row);
          break;
        default:
          break;
      }
    },


    /** 查询部门下拉树结构 */
    getDeptTree() {
      this.$store
        .dispatch("getDeptTree")
        .then((response) => {
          this.deptOptions = response;
        })
        .catch((error) => {
          this.deptOptions = [];
        });
    },
    /** 查询岗位列表,角色列表 */
    getPostAndRoleList() {
      this.$store
        .dispatch("getPostList")
        .then((response) => {


          this.postOptions = response.posts;
          console.log(this.postOptions, 1304);
          this.roleOptions = response.roles;
        })
        .catch((error) => {
          this.postOptions = [];
          this.roleOptions = [];
        });
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "school/teacher/importTemplate",
        {},
        `老师信息模板_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    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();
    },
    /** 导出 */
    exportFile(callback) {
      const ids = this.ids;
      const options = [
        { type: ExportType.TOTAL, path: "/school/teacher/export", params: {} },
        {
          type: ExportType.SELECT,
          path: "/school/teacher/export/" + ids,
          params: {},
        },
        {
          type: ExportType.QUERY,
          path: "/school/teacher/export",
          params: this.queryParams,
        },
      ];
      callback(options, `老师信息${new Date().getTime()}.xlsx`);
    },

    /** 是否可以被勾选 */
    isSelected(row, index) {
      if (row.id == 1) {
        return false;
      }
      return true;
    },
    switchChange(row, status) {
      this.$modal
        .confirm(status === '1' ? '是否确认停用此用户状态？' : '是否确认启用此用户状态？')
        .then(() => {
          this.$modal.loading('正在修改状态，请稍等...')
          statusChange(status, row.id)
            .then(response => {
              this.$modal.closeLoading()
              this.$modal.msgSuccess('修改成功')
            })
        })
        .catch(() => {
          this.$modal.closeLoading()
        })
      // console.log(row, status, 56565656)
      // statusChange(status, row.id).then(() => {

      // })
    }

  },
};
</script>
<style scoped>
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 176px;
  height: 176px;
}

.avatar-uploader :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;
}

.pwd {
  text-security: disc;
  -webkit-text-security: disc;
}
</style>
