<template>
  <section
    v-loading.fullscreen="loading"
    class="content"
    element-loading-text="请稍后..."
  >
    <div class="part-box">
      <h2 class="part-box-title">用户管理</h2>
      <!-- 搜索 -->
      <el-form class="part-filter-form" inline :model="searchForm">
        <el-form-item v-if="isSuperAdmin" label="学校">
          <el-select
            v-model="searchForm.rootOrgId"
            placeholder="请选择"
            :disabled="!isSuperAdmin"
            filterable
            @change="rootOrgChanged4Search"
          >
            <el-option
              v-for="item in rootSchoolSelect"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="!onlySubjectTeacher" label="角色">
          <el-select v-model="searchForm.roleId" clearable placeholder="请选择">
            <el-option
              v-for="item in roleList4Search"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="课程">
          <el-select
            v-model="searchForm.courseId"
            class="input"
            :remote-method="getCourses4Search"
            :loading="courseLoading4Search"
            remote
            filterable
            clearable
            placeholder="请选择"
            @clear="getCourses4Search('')"
          >
            <el-option
              v-for="item in courseList4Search"
              :key="item.id"
              :label="item.name + ' - ' + item.code"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="登录名">
          <el-input
            v-model="searchForm.loginName"
            placeholder="请输入登录名"
            maxlength="20"
          />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入姓名"
            maxlength="20"
          />
        </el-form-item>

        <el-form-item label="状态">
          <el-select v-model="searchForm.enable" class="input">
            <el-option label="未选择" value=""></el-option>
            <el-option label="已启用" value="true"></el-option>
            <el-option label="已禁用" value="false"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="danger" @click="handleSearchBtn"> 查询 </el-button>
          <el-button type="danger" plain @click="resetEcsFormSearch">
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <div class="part-box-action">
        <div>
          <el-button
            type="success"
            plain
            icon="icon icon-play"
            :disabled="noBatchSelected"
            @click="enableByIds"
            >启用
          </el-button>
          <el-button
            type="danger"
            plain
            icon="icon icon-delete"
            :disabled="noBatchSelected"
            @click="disableByIds"
            >禁用
          </el-button>
        </div>
        <div>
          <el-button
            type="primary"
            icon="icon icon-plus-white"
            @click="openAddingDialog"
            >新增
          </el-button>
          <el-button
            type="primary"
            plain
            icon="icon icon-import"
            @click="impUser"
            >导入
          </el-button>
        </div>
      </div>
    </div>

    <div class="part-box">
      <!-- 页面列表 -->
      <el-table
        ref="table"
        :data="tableData"
        resizable
        @selection-change="selectChange"
      >
        <el-table-column
          type="selection"
          width="50"
          align="center"
        ></el-table-column>
        <el-table-column prop="id" width="80" label="ID" />
        <el-table-column prop="name" width="120" label="姓名" />
        <el-table-column prop="loginName" width="100" label="登录名" />
        <el-table-column prop="rootOrgName" label="顶级机构" />
        <!-- <el-table-column prop="roleNamesStr" width="110" label="角色" /> -->
        <el-table-column width="120" label="角色">
          <span
            slot-scope="scope"
            v-html="scope.row.roleNamesStr.replace(/,/g, '<br />')"
          >
          </span>
        </el-table-column>
        <el-table-column width="100" label="审核权限">
          <span slot-scope="scope">{{
            scope.row.auditAuthority | auditAuthorityFilter
          }}</span>
        </el-table-column>
        <el-table-column width="120" label="关联课程">
          <span
            slot-scope="scope"
            v-html="
              scope.row.courseNamesStr &&
              scope.row.courseNamesStr.replace(/,/g, '<br />')
            "
          >
          </span>
        </el-table-column>
        <el-table-column
          sortable
          prop="updateTime"
          width="160"
          label="更新时间"
        />
        <el-table-column width="50" label="状态">
          <span slot-scope="scope">
            <span v-if="scope.row.enable">
              <el-tooltip
                class="item"
                effect="dark"
                content="启用"
                placement="left"
              >
                <i class="icon icon-right"></i>
              </el-tooltip>
            </span>
            <span v-else>
              <el-tooltip
                class="item"
                effect="dark"
                content="禁用"
                placement="left"
              >
                <i class="icon icon-error"></i>
              </el-tooltip>
            </span>
          </span>
        </el-table-column>
        <el-table-column width="170" label="操作">
          <div slot-scope="scope">
            <div v-if="showBtn(scope.row)">
              <el-button
                v-if="!scope.row.enable"
                size="mini"
                type="primary"
                plain
                @click="enableById(scope.row)"
              >
                启用
              </el-button>
              <el-button
                v-if="scope.row.enable"
                size="mini"
                plain
                type="danger"
                @click="disableById(scope.row)"
              >
                禁用
              </el-button>
              <el-dropdown>
                <el-button type="primary" plain size="mini">
                  更多<i class="el-icon-more el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown" class="action-dropdown">
                  <el-dropdown-item>
                    <el-button
                      v-if="showUserDataRuleSetting(scope.row)"
                      size="mini"
                      type="primary"
                      plain
                      @click="setPrivilege(scope.row)"
                      >权限设置
                    </el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button
                      size="mini"
                      type="primary"
                      plain
                      @click="openUpdateDialog(scope.row)"
                      >编辑
                    </el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button
                      v-if="false"
                      size="mini"
                      type="danger"
                      plain
                      @click="deleteById(scope.row)"
                      >删除
                    </el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button
                      size="mini"
                      type="danger"
                      plain
                      @click="resetPass(scope.row)"
                    >
                      重置密码
                    </el-button>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </div>
        </el-table-column>
      </el-table>
      <div class="part-page">
        <el-pagination
          :current-page.sync="currentPage"
          :page-size.sync="pageSize"
          :page-sizes="[10, 20, 50, 100, 200, 300]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>

    <!-- 添加用户信息弹出框 -->
    <el-dialog
      title="新增用户"
      width="620px"
      :visible.sync="addingDialog"
      :modal="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
      custom-class="side-dialog"
    >
      <el-form
        ref="addingForm"
        inline-message
        class="form-tight"
        :model="userForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input
            v-model="userForm.name"
            class="dialog-input-width"
            auto-complete="off"
            placeholder="请输入姓名"
            maxlength="20"
          />
        </el-form-item>
        <el-form-item label="登录名" prop="loginName">
          <el-input
            v-model="userForm.loginName"
            class="dialog-input-width"
            auto-complete="off"
            placeholder="请输入登录名"
            maxlength="20"
          />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="userForm.password"
            class="dialog-input-width"
            auto-complete="off"
            placeholder="请输入密码"
          />
        </el-form-item>
        <el-form-item v-if="isSuperAdmin" label="学校" prop="rootOrgId">
          <el-select
            v-model="userForm.rootOrgId"
            class="dialog-input-width"
            placeholder="请选择"
            :disabled="!isSuperAdmin"
            filterable
            @change="rootOrgChanged4InsertOrUpdate"
          >
            <el-option
              v-for="item in rootSchoolSelect"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select
            v-model="userForm.roleId"
            class="dialog-input-width"
            placeholder="请选择"
          >
            <el-option
              v-for="item in roleList4InsertOrUpdateWithoutSuperAdmin"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId"
              :disabled="roleDis(item.roleCode)"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="enableStr" class="pull_right_sm">
            <el-radio label="true">启用</el-radio>
            <el-radio label="false">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="add">保存</el-button>
        <el-button type="danger" plain @click="addingDialog = false"
          >取消</el-button
        >
      </div>
    </el-dialog>

    <!-- 修改用户信息弹出框 -->
    <el-dialog
      title="编辑用户"
      width="620px"
      :visible.sync="updateDialog"
      :modal="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
      custom-class="side-dialog"
    >
      <el-form
        ref="updateForm"
        inline-message
        class="form-tight"
        :model="userForm"
        :rules="rules"
        label-position="right"
        label-width="80px"
      >
        <el-form-item label="ID">
          <el-input
            v-model="userForm.id"
            class="dialog-input-width"
            :disabled="true"
          />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input
            v-model="userForm.name"
            class="dialog-input-width"
            auto-complete="off"
            placeholder="请输入姓名"
            maxlength="20"
          />
        </el-form-item>
        <el-form-item label="登录名" prop="loginName">
          <el-input
            v-model="userForm.loginName"
            class="dialog-input-width"
            auto-complete="off"
            placeholder="请输入登录名"
            maxlength="20"
          />
        </el-form-item>
        <el-form-item v-if="isSuperAdmin" label="学校" prop="rootOrgId">
          <el-select
            v-model="userForm.rootOrgId"
            class="dialog-input-width"
            placeholder="请选择"
            :disabled="true"
          >
            <el-option
              v-for="item in rootSchoolSelect"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select
            v-model="userForm.roleId"
            class="dialog-input-width"
            placeholder="请选择"
            :disabled="rowIsSuperAdmin"
          >
            <el-option
              v-for="item in roleList4InsertOrUpdate"
              :key="item.roleId"
              :label="item.roleName"
              :disabled="roleDis(item.roleCode)"
              :value="item.roleId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group
            v-model="enableStr"
            class="pull_right_sm"
            :disabled="rowIsSuperAdmin"
          >
            <el-radio label="true">启用</el-radio>
            <el-radio label="false">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="update">保存</el-button>
        <el-button type="danger" plain @click="updateDialog = false"
          >取消</el-button
        >
      </div>
    </el-dialog>
    <!-- 导入弹窗 -->
    <el-dialog
      title="导入用户"
      width="520px"
      :visible.sync="impDialog"
      :modal="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
      custom-class="side-dialog"
    >
      <el-form>
        <el-form-item style="margin-left: 20px">
          <el-upload
            ref="upload"
            class="form_left"
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            :action="uploadAction"
            :headers="uploadHeaders"
            :data="uploadData"
            :on-success="uploadSuccess"
            :on-error="uploadError"
            :file-list="fileList"
            :auto-upload="false"
            :multiple="false"
          >
            <el-button
              slot="trigger"
              size="small"
              type="primary"
              icon="icon icon-search-white"
            >
              选择文件
            </el-button>
            <el-button
              size="small"
              type="primary"
              icon="icon icon-save-white"
              @click="submitUpload"
            >
              确认上传
            </el-button>
            <el-button
              size="small"
              type="primary"
              icon="icon icon-delete-white"
              @click="removeFile"
            >
              清空文件
            </el-button>
            <el-button
              size="small"
              type="primary"
              icon="icon icon-export-white"
              @click="exportFile"
            >
              下载模板
            </el-button>
            <div slot="tip" class="el-upload__tip">只能上传xlsx文件</div>
          </el-upload>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 导入错误信息列表 -->
    <el-dialog title="错误提示" :visible.sync="errDialog" append-to-body>
      <div
        v-for="errMessage in errMessages"
        :key="errMessage.lineNum"
        class="text-danger"
      >
        第{{ errMessage.lineNum }}行：{{ errMessage.msg }}
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="errDialog = false">确定</el-button>
      </span>
    </el-dialog>
  </section>
</template>

<script>
import { QUESTION_API } from "@/constants/constants.js";
import { mapState } from "vuex";

export default {
  name: "User",
  data() {
    var validateRootOrg = (rule, value, callback) => {
      if (0 != value && !value) {
        callback(new Error("请选择学校"));
      } else {
        callback();
      }
    };
    var validateRoles = (rule, value, callback) => {
      if (0 != value && !value) {
        callback(new Error("请选择角色"));
      } else {
        callback();
      }
    };
    return {
      impDialog: false,
      uploadAction: QUESTION_API + "/user/import",
      uploadHeaders: {},
      uploadData: {},
      errMessages: [],
      errDialog: false,
      fileLoading: false,
      fileList: [],

      courseList4Search: [],
      courseLoading4Search: false,
      rolePrivileges: {
        user_data_rule_setting: false,
      },
      loading: false,
      orgLoading4InsertOrUpdate: false,
      roleList4Search: [],
      roleList4InsertOrUpdate: [],
      rootOrgList: [],
      orgList4InsertOrUpdate: [],
      searchForm: {
        courseId: "",
        name: "",
        loginName: "",
        enable: "",
        rootOrgId: "",
        roleId: "",
      },
      userForm: {
        id: null,
        name: "",
        loginName: "",
        password: "",
        phoneNumber: "",
        enable: true,
        rootOrgId: null,
        orgId: null,
        roleId: null,
      },
      enableStr: "true",

      tempOrgList: [],
      userId: "",
      selectedUserIds: [],
      selectedUserToCopy: null,
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 10,
      addingDialog: false,
      updateDialog: false,
      rowIsSuperAdmin: false,
      rules: {
        name: [
          {
            required: true,
            max: 20,
            message: "请输入姓名，最多20字符",
            trigger: "blur",
          },
        ],
        loginName: [
          {
            required: true,
            max: 20,
            message: "请输入登录名，最多20字符",
            trigger: "blur",
          },
        ],
        password: [
          {
            validator: (rule, value, callback) => {
              if (
                value &&
                (/^([0-9]+|[a-z]+|[A-Z]+)$/.test(value) ||
                  !/^[a-zA-Z0-9_]+$/.test(value))
              ) {
                callback(
                  new Error("密码只能大写字母、小写字母、数字至少两种组成")
                );
              } else {
                callback();
              }
            },
            trigger: "change",
          },
          {
            required: true,
            min: 8,
            max: 16,
            message: "密码只能8-16个字符",
            trigger: "change",
          },
        ],
        phoneNumber: [
          // {
          //   message: "请输入联系方式",
          //   trigger: "blur"
          // }
        ],
        rootOrgId: [
          {
            validator: validateRootOrg,
            trigger: "blur",
          },
        ],
        orgId: [],
        roleId: [
          {
            required: true,
            validator: validateRoles,
            trigger: ["blur", "change"],
          },
        ],
      },
    };
  },
  computed: {
    ...mapState({
      user: (state) => state.user,
    }),
    userIds() {
      var userIds = "";
      for (let userId of this.selectedUserIds) {
        if (!userIds) {
          userIds += userId;
        } else {
          userIds += "," + userId;
        }
      }
      return userIds;
    },
    noBatchSelected() {
      return this.selectedUserIds.length === 0;
    },
    roleList4InsertOrUpdateWithoutSuperAdmin() {
      return this.roleList4InsertOrUpdate.filter(
        (item) => item.roleCode != "SUPER_ADMIN"
      );
    },
    isSubjectTeacher() {
      return this.user.roleList.some(
        (role) => role.roleCode == "SUBJECT_TEACHER"
      );
    },
    onlySubjectTeacher() {
      if (this.isAdmin) {
        return false;
      } else {
        return this.user.roleList.some(
          (role) => role.roleCode == "SUBJECT_TEACHER"
        );
      }
    },
    isSuperAdmin() {
      return this.user.roleList.some((role) => role.roleCode == "SUPER_ADMIN");
    },
    isAdmin() {
      return this.user.roleList.some(
        (role) => role.roleCode == "SUPER_ADMIN" || role.roleCode == "ADMIN"
      );
    },
    rootSchoolSelect() {
      let rootSchools = [];
      for (let i = 0; i < this.rootOrgList.length; i++) {
        let info = {
          name: this.rootOrgList[i].name + "（" + this.rootOrgList[i].id + "）",
          id: this.rootOrgList[i].id,
        };
        rootSchools.push(info);
      }
      return rootSchools;
    },
  },
  //初始化查询
  created() {
    this.initPrivileges();
    this.init();
    this.uploadHeaders = {
      key: this.user.key,
      token: this.user.token,
    };
  },
  methods: {
    roleDis(code) {
      if (this.onlySubjectTeacher && code != "ASSIGN_TEACHER") {
        return true;
      } else {
        return false;
      }
    },
    impUser() {
      this.impDialog = true;
      this.initUpload();
    },
    initUpload() {
      this.fileList = [];
    },
    uploadSuccess(response) {
      if (!response.hasError) {
        this.$notify({
          message: "上传成功",
          type: "success",
        });
        this.fileLoading = false;
        this.impDialog = false;
        this.searchForm();
      } else {
        this.fileLoading = false;
        this.impDialog = false;
        this.errMessages = response.failRecords;
        this.errDialog = true;
      }
    },
    uploadError(response) {
      var json = JSON.parse(response.message);
      if (response.status == 500) {
        this.$notify({
          message: json.desc,
          type: "error",
        });
      }
      this.fileLoading = false;
    },
    //确定上传
    submitUpload() {
      if (!this.checkUpload()) {
        return false;
      }
      this.$refs.upload.submit();
      this.fileLoading = true;
    },
    checkUpload() {
      var fileList = this.$refs.upload.uploadFiles;
      if (fileList.length == 0) {
        this.$notify({
          message: "上传文件不能为空",
          type: "error",
        });
        return false;
      }
      if (fileList.length > 1) {
        this.$notify({
          message: "每次只能上传一个文件",
          type: "error",
        });
        return false;
      }
      for (let file of fileList) {
        if (!file.name.endsWith(".xlsx")) {
          this.$notify({
            message: "上传文件必须为xlsx格式",
            type: "error",
          });
          this.initUpload();
          return false;
        }
      }
      return true;
    },
    //清空文件
    removeFile() {
      // this.fileList = [];
      this.$refs.upload.clearFiles();
    },
    //下载模板
    exportFile() {
      window.location.href =
        QUESTION_API +
        "/user/importTemplate?$key=" +
        this.user.key +
        "&$token=" +
        this.user.token;
    },
    getCourses4Search(query) {
      this.courseLoading4Search = true;
      this.$httpWithMsg
        .get(QUESTION_API + "/course/query?name=" + query)
        .then((response) => {
          this.courseList4Search = response.data;
          this.courseLoading4Search = false;
        });
    },
    resetEcsFormSearch() {
      this.searchForm = Object.assign(this.searchForm, {
        roleId: "",
        courseId: "",
        loginName: "",
        name: "",
        enable: "",
      });
    },
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.search();
    },
    validateOrg(rule, value, callback) {
      if (0 != value && !value) {
        callback(new Error("请选择子机构"));
      } else {
        callback();
      }
    },
    rootOrgChanged4Search() {
      var url =
        QUESTION_API +
        "/rolePrivilege/getRoles?includeSuperAdmin=" +
        true +
        "&rootOrgId=" +
        this.searchForm.rootOrgId;
      this.$httpWithMsg.post(url).then((response) => {
        this.roleList4Search = response.data;
      });
    },
    rootOrgChanged4InsertOrUpdate() {
      this.orgList4InsertOrUpdate = [];

      var url =
        QUESTION_API +
        "/rolePrivilege/getRoles?rootOrgId=" +
        this.userForm.rootOrgId;
      this.$httpWithMsg.post(url).then((response) => {
        this.roleList4InsertOrUpdate = response.data;
      });
    },
    getOrgList4InsertOrUpdate(query) {
      this.orgLoading4InsertOrUpdate = true;
      var url =
        QUESTION_API +
        "/org/query?" +
        new URLSearchParams({
          name: query,
          rootOrgId: this.userForm.rootOrgId,
        });
      this.$httpWithMsg
        .get(url)
        .then((response) => {
          this.orgList4InsertOrUpdate = response.data;
          this.orgLoading4InsertOrUpdate = false;
        })
        .catch(() => {
          this.orgLoading4InsertOrUpdate = false;
        });
    },
    getTag(status) {
      if (status == true) {
        return "success";
      } else if (status == false) {
        return "danger";
      }
      return status;
    },
    getLevel(level) {
      if (level == "ZSB") {
        return "专升本";
      } else if (level == "GQZ") {
        return "高起专";
      }
      return level;
    },
    handleSearchBtn() {
      this.currentPage = 1;
      this.search();
    },
    search() {
      let searchLock = true;
      setTimeout(() => {
        if (searchLock) {
          this.loading = true;
        }
      }, 500);
      var param = new URLSearchParams(this.searchForm);
      var url =
        QUESTION_API +
        "/user/all/" +
        this.currentPage +
        "/" +
        this.pageSize +
        "?" +
        param;
      this.$httpWithMsg
        .get(url)
        .then((response) => {
          // console.log(response);
          this.tableData = response.data.content;
          this.total = response.data.totalElements;
          this.loading = false;
        })
        .finally(() => {
          searchLock = false;
          this.loading = false;
        });
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.search();
    },
    selectChange(row) {
      this.selectedUserIds = [];
      row.forEach((element) => {
        this.selectedUserIds.push(element.id);
      });
    },
    //新增
    openAddingDialog() {
      if (this.$refs.addingForm) {
        this.$refs.addingForm.resetFields();
      }
      if (this.$refs.updateForm) {
        this.$refs.updateForm.resetFields();
      }
      this.addingDialog = true;
      this.userForm.name = "";
      this.userForm.loginName = "";
      this.userForm.password = "";
      this.userForm.phoneNumber = "";
      this.userForm.roleId = null;
      this.userForm.orgId = null;
      this.enableStr = "true";
      this.orgList4InsertOrUpdate = [];
    },
    //修改
    openUpdateDialog(row) {
      if (this.$refs.updateForm) {
        this.$refs.updateForm.resetFields();
      }
      if (this.$refs.addingForm) {
        this.$refs.addingForm.resetFields();
      }

      this.updateDialog = true;
      this.userForm.id = row.id;
      this.userForm.roleId = row.roleIds[0];
      this.userForm.name = row.name;
      this.userForm.loginName = row.loginName;
      this.enableStr = row.enable ? "true" : "false";
      this.userForm.phoneNumber = row.phoneNumber;
      this.userForm.password = null;
      this.userForm.rootOrgId = row.rootOrgId;
      this.rowIsSuperAdmin = false;
      for (let roleCode of row.roleCodes) {
        if (roleCode == "SUPER_ADMIN") {
          this.rowIsSuperAdmin = true;
          break;
        }
      }

      this.rootOrgChanged4InsertOrUpdate();
      this.orgList4InsertOrUpdate = [{ id: row.orgId, name: row.orgName }];
      this.userForm.orgId = row.orgId;
    },
    exportUser() {
      var param = new URLSearchParams(this.searchForm);
      window.open(QUESTION_API + "/user/export?" + param);
    },
    // 设置权限
    setPrivilege(row) {
      window.sessionStorage.setItem(
        "userPageCache",
        JSON.stringify({
          searchFilter: this.userForm,
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          total: this.total,
        })
      );
      this.$router.push(`./user/data_previllege/${row.rootOrgId}/${row.id}`);
    },
    //保存
    add() {
      var url = QUESTION_API + "/user";
      this.$refs.addingForm.validate((valid) => {
        if (valid) {
          this.userForm.enable = this.enableStr == "true";
          this.$httpWithMsg.post(url, this.userForm).then(() => {
            this.$notify({
              type: "success",
              message: "添加成功",
            });
            this.search();
            this.addingDialog = false;
          });
        } else {
          return false;
        }
      });
    },
    //保存
    update() {
      var url = QUESTION_API + "/user";
      this.$refs.updateForm.validate((valid) => {
        if (valid) {
          this.userForm.enable = this.enableStr == "true";
          this.$httpWithMsg.put(url, this.userForm).then(() => {
            this.$notify({
              type: "success",
              message: "添加成功",
            });
            this.search();
            this.updateDialog = false;
          });
        } else {
          return false;
        }
      });
    },
    //重置密码
    resetPass(row) {
      this.$confirm("是否重置密码？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var url = QUESTION_API + "/user/resetPass/" + row.id;
          this.$httpWithMsg.put(url).then(() => {
            this.$notify({
              type: "success",
              message: "重置成功！",
            });
            return this.search();
          });
        })
        .catch((e) => console.log(e));
    },
    //删除单个数据
    deleteById(row) {
      this.$confirm("是否删除该用户？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        var url = QUESTION_API + "/user/" + row.id;
        this.$httpWithMsg.delete(url).then(() => {
          this.$notify({
            type: "success",
            message: "删除成功！",
          });
          return this.search();
        });
      });
    },
    //删除多条数据
    deleteByIds() {
      if (this.selectedUserIds.length === 0) {
        this.$notify({
          type: "warning",
          message: "请选择要删除的用户",
        });
      } else {
        this.$confirm("是否删除这些用户？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "error",
        }).then(() => {
          var url = QUESTION_API + "/user/" + this.userIds;
          this.$httpWithMsg.delete(url).then(() => {
            this.$notify({
              type: "success",
              message: "删除成功！",
            });
            this.search();
          });
        });
      }
    },
    //启用
    enableByIds() {
      if (this.selectedUserIds.length === 0) {
        this.$notify({
          type: "warning",
          message: "请选择要启用的用户",
        });
      } else {
        this.$confirm("是否启用这些用户？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          var url = QUESTION_API + "/user/enable/" + this.userIds;
          this.$httpWithMsg.put(url, {}).then(() => {
            this.$notify({
              type: "success",
              message: "启用成功！",
            });
            return this.search();
          });
        });
      }
    },
    enableById(row) {
      this.$confirm("是否启用该用户？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        var url = QUESTION_API + "/user/enable/" + row.id;
        this.$httpWithMsg.put(url, {}).then(() => {
          this.$notify({
            type: "success",
            message: "启用成功！",
          });
          this.search();
        });
      });
    },
    //禁用
    disableByIds() {
      if (this.selectedUserIds.length === 0) {
        this.$notify({
          type: "warning",
          message: "请选择要禁用的用户",
        });
      } else {
        this.$confirm("是否禁用这些用户？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "error",
        }).then(() => {
          var url = QUESTION_API + "/user/disable/" + this.userIds;
          this.$httpWithMsg.put(url, {}).then(() => {
            this.$notify({
              type: "success",
              message: "禁用成功！",
            });
            this.search();
          });
        });
      }
    },
    //禁用
    disableById(row) {
      this.$confirm("是否禁用该用户？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error",
      }).then(() => {
        var url = QUESTION_API + "/user/disable/" + row.id;
        this.$httpWithMsg.put(url, {}).then(() => {
          this.$notify({
            type: "success",
            message: "禁用成功！",
          });
          this.search();
        });
      });
    },
    /*初始化*/
    init() {
      this.searchForm.rootOrgId = this.user.rootOrgId;
      this.userForm.rootOrgId = this.user.rootOrgId;

      var url1 = QUESTION_API + "/org/getRootOrgList";
      var url2 =
        QUESTION_API +
        "/rolePrivilege/getRoles?includeSuperAdmin=true&rootOrgId=" +
        this.user.rootOrgId;

      Promise.all([
        this.$httpWithMsg.get(url1),
        this.$httpWithMsg.post(url2),
      ]).then(([resp1, resp2]) => {
        this.rootOrgList = resp1.data;
        this.roleList4Search = resp2.data;
        this.roleList4InsertOrUpdate = resp2.data;

        const cacheInfo = window.sessionStorage.getItem("userPageCache");
        if (cacheInfo) {
          const { searchFilter, currentPage, pageSize, total } =
            JSON.parse(cacheInfo);
          this.userForm = searchFilter;
          this.currentPage = currentPage;
          this.pageSize = pageSize;
          this.total = total;
          window.sessionStorage.removeItem("userPageCache");
        }
        this.search();
      });
    },
    initPrivileges() {
      let params = new URLSearchParams();
      params.append(
        "privilegeCodes",
        Object.keys(this.rolePrivileges).toString()
      );
      var url = QUESTION_API + "/rolePrivilege/checkPrivileges?" + params;
      this.$httpWithMsg.post(url).then((response) => {
        this.rolePrivileges = response.data;
      });
      this.getCourses4Search("");
    },
    showUserDataRuleSetting(row) {
      let roleCodes = row.roleCodes;

      for (let n = 0; n < roleCodes.length; n++) {
        let roleCode = roleCodes[n];
        if (roleCode == "SUPER_ADMIN" || roleCode == "ADMIN") {
          return false;
        }
      }

      return true;
    },
    showBtn(row) {
      let roleCodes = row.roleCodes;

      for (let n = 0; n < roleCodes.length; n++) {
        let roleCode = roleCodes[n];
        if (roleCode == "SUPER_ADMIN") {
          return false;
        }
      }

      return true;
    },
  },
};
</script>
