<template>
  <BasicLayout>
    <template #wrapper>
      <el-card class="box-card">
        <div class="org_header">
          <span class="subject">用户管理</span>
          <div class="header_btn_box">
            <el-button size="mini" @click="resetQuery()">刷新列表</el-button>
            <el-dropdown class="m20" @command="userAdd">
              <el-button type="primary" size="mini">
                添加用户<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="1">单个添加</el-dropdown-item>
                <el-dropdown-item command="2">批量添加</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </div>
        <el-row
          :gutter="18"
          class="mt10 el-flex"
          justify="space-between"
          type="flex"
        >
          <el-col :span="14" class="mt10 selectOrg">
            <el-form :model="queryParams" :inline="true">
              <el-form-item label="" prop="org">
                <el-cascader
                  placeholder="选择组织"
                  v-model="queryParams.deptIDList"
                  :options="orgList"
                  @change="querySelectOrg"
                  clearable
                  size="small"
                  :props="{
                    value: 'id',
                    label: 'name',
                    checkStrictly: true,
                    emitPath: false,
                  }"
                >
                  <template slot-scope="{ data }">
                    <span>{{ data.name }}</span>
                  </template>
                </el-cascader>
              </el-form-item>
              <el-form-item label="" prop="occ">
                <el-select
                  v-model="queryParams.occ"
                  placeholder="选择岗位"
                  size="small"
                  clearable
                  @change="getBlurValue(queryParams.occ)"
                >
                  <el-option
                    v-for="(item, index) in queryOccList"
                    :key="index"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="" prop="query">
                <el-input
                  prefix-icon="el-icon-search"
                  v-model="queryParams.filter"
                  placeholder="请输入关键字搜索"
                  clearable
                  size="small"
                  @keyup.enter.native="filterQuery"
                ></el-input>
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="1.5" class="mb8 mt10">
            <!-- <el-button size="mini" @click="openImport()">Excel导入 </el-button> -->
          </el-col>
        </el-row>
        <el-table
          ref="multipleTable"
          :data="tableUser"
          tooltip-effect="dark"
          style="width: 100%"
          v-loading="loading"
          @selection-change="handleSelectionChange"
          @sort-change="handleSortChang"
        >
          <el-table-column type="selection" width="45"> </el-table-column>
          <el-table-column prop="name" label="姓名"></el-table-column>
          <el-table-column prop="phone" label="手机号"></el-table-column>
          <el-table-column label="组织" align="left" prop="deptNames">
            <template slot-scope="scope">
              <div v-for="(v, k) in scope.row.deptNames" :key="k">{{ v }}</div>
            </template>
          </el-table-column>
          <el-table-column label="岗位" align="left" prop="occNames">
            <template slot-scope="scope">
              <div v-for="(val, key) in scope.row.occNames" :key="key">
                {{ val }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="创建人/时间"
            align="left"
            prop="createdTime"
            :formatter="parseTime"
            sortable="custom"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.creatorName }}</span
              ><br />
              <span>{{ parseTime(scope.row.createdTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="address" label="操作" align="center">
            <template slot-scope="scope">
              <div>
                <el-button
                  @click.native.prevent="editRow(scope.row)"
                  type="text"
                  size="mini"
                >
                  编辑
                </el-button>
                <el-button
                  @click.native.prevent="delRow(scope.row)"
                  type="text"
                  size="mini"
                >
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-row
          :gutter="24"
          class="mb8 mt10"
          justify="space-between"
          type="flex"
        >
          <el-col :span="12">
            <div style="margin-top: 10px">
              <el-button
                size="mini"
                :disabled="isDisabled"
                @click="handleDelUsers()"
                >删除
              </el-button>
              <el-button size="mini" :disabled="isDisabled" @click="setOrgs()"
                >设置组织
              </el-button>
              <el-button @click="setOcc()" size="mini" :disabled="isDisabled"
                >设置岗位
              </el-button>
            </div>
          </el-col>
          <el-col
            :span="12"
            class="mb8 mt10 selectOrg"
            style="justify-content: end"
          >
            <pagination
              v-show="total > 0"
              :total="total"
              :page.sync="pageIndex"
              :limit.sync="queryParams.limit"
              @pagination="getListUsers"
            />
          </el-col>
        </el-row>
        <!-- 弹窗 -->
        <el-dialog
          :visible.sync="dialogVisible"
          :width="width"
          :close-on-click-modal="false"
        >
          <div slot="title" class="dialog-title">
            <div class="dialog-icon mr20"></div>
            <span class="dialog-tip mr20">{{ title }}</span>
          </div>
          <div class="el-flex-center">
            <div class="center-box" v-if="multiple == 1">
              <span class="dialog-tip mr20">基本资料</span>
            </div>
            <!-- <el-alert v-if="multiple == 2" style="margin-bottom:20px" :closable="false"
              type="warning"
              description="初始密码为12345#hx"
              show-icon>
            </el-alert> -->
            <!-- 添加单个用户 -->
            <el-form
              :model="employees"
              v-if="multiple == 1"
              :rules="addUser"
              ref="employee"
            >
              <el-form-item
                label="手机号"
                :label-width="formLabelWidth"
                prop="phone"
              >
                <el-input
                  :maxlength="11"
                  v-model.number="employees.phone"
                  placeholder="请输入手机号"
                  autocomplete="off"
                  class="input_width"
                  size="small"
                ></el-input>
              </el-form-item>
              <el-form-item
                label="密码"
                :label-width="formLabelWidth"
                prop="password"
              >
                <el-input
                  v-model="employees.password"
                  type="password"
                  autocomplete="off"
                  placeholder="必须包含字母、数字及特殊符号，且不小于8位"
                  class="input_width"
                  size="small"
                ></el-input>
              </el-form-item>
              <el-form-item
                label="确认密码"
                :label-width="formLabelWidth"
                prop="confirm"
              >
                <el-input
                  v-model="employees.confirm"
                  type="password"
                  autocomplete="off"
                  placeholder="请再次输入新密码"
                  class="input_width"
                  size="small"
                ></el-input>
              </el-form-item>
              <el-form-item
                label="姓名"
                :label-width="formLabelWidth"
                prop="realName"
              >
                <el-input
                  v-model="employees.realName"
                  autocomplete="off"
                  placeholder="请输入姓名"
                  class="input_width"
                  size="small"
                ></el-input>
              </el-form-item>
              <el-form-item
                label="组织"
                :label-width="formLabelWidth"
                size="small"
                required
                prop="deptIDList"
              >
                <el-cascader
                  v-model="employees.deptIDList"
                  :options="orgList"
                  @change="handleSelectOrg"
                  :props="{
                    value: 'id',
                    label: 'name',
                    checkStrictly: true,
                    emitPath: false,
                  }"
                >
                  <template slot-scope="{ data }">
                    <span>{{ data.name }}</span>
                  </template>
                </el-cascader>
              </el-form-item>
              <el-form-item
                :label-width="formLabelWidth"
                v-for="(item, index) in employees.deptIDLists"
                :key="index"
                size="small"
                prop="orgs"
              >
                <el-cascader
                  ref="cascader"
                  v-model="item.deptIDItem"
                  :options="orgList"
                  :props="{
                    value: 'id',
                    label: 'name',
                    checkStrictly: true,
                    emitPath: false,
                  }"
                  @change="handleSelectOrgs(item.deptIDItem)"
                >
                </el-cascader>
                <el-button plain @click="delItemOrgs(item)" class="ml0"
                  >删除</el-button
                >
              </el-form-item>

              <el-form-item
                label=""
                :label-width="formLabelWidth"
                style="margin-top: -26px"
              >
                <i
                  class="el-icon-circle-plus-outline"
                  style="font-size: 16px; color: #1e5aff"
                >
                </i>
                <el-button
                  type="text"
                  @click="addUserFormOrg()"
                  size="mini"
                  style="margin-left: -6px"
                  >添加</el-button
                >
              </el-form-item>
              <el-form-item
                label="岗位"
                :label-width="formLabelWidth"
                size="small"
              >
                <el-cascader
                  v-model="employees.occIDList"
                  :options="queryOccList"
                  :props="{
                    value: 'id',
                    label: 'name',
                  }"
                  @change="handleSelectOcc"
                >
                </el-cascader>
              </el-form-item>
              <el-form-item
                :label-width="formLabelWidth"
                v-for="(item, index) in employees.occIDLists"
                :key="index"
                size="small"
              >
                <el-cascader
                  v-model="item.occIDItem"
                  :props="{
                    value: 'id',
                    label: 'name',
                  }"
                  :options="queryOccList"
                  @change="handleSelectOccS"
                ></el-cascader>
                <el-button plain @click="delItemOccs(item)" class="ml0"
                  >删除</el-button
                >
              </el-form-item>
              <el-form-item
                label=""
                :label-width="formLabelWidth"
                style="margin-top: -26px"
              >
                <i
                  class="el-icon-circle-plus-outline"
                  style="font-size: 16px; color: #1e5aff"
                ></i>
                <el-button
                  type="text"
                  @click="addUserFormOcc()"
                  size="mini"
                  style="margin-left: -6px"
                  >添加</el-button
                >
              </el-form-item>

              <el-form-item
                label="邮箱"
                :label-width="formLabelWidth"
                prop="email"
              >
                <el-input
                  v-model="employees.email"
                  autocomplete="off"
                  placeholder="请输入邮箱"
                  class="input_width"
                  size="small"
                ></el-input>
              </el-form-item>
            </el-form>

            <!-- 批量添加用户 -->
            <el-form
              :model="addForms"
              ref="employees"
              v-if="multiple == 2"
              :inline="true"
              style="width: 996px"
            >
              <div class="mb20 pb5">
                <el-row
                  :gutter="18"
                  type="flex"
                  justify="space-between"
                  style="margin: 0"
                >
                  <el-col :span="5" class="col-style"> 手机号（必填） </el-col>
                  <el-col :span="5" class="col-style"> 姓名（必填） </el-col>
                  <el-col :span="5" class="col-style"> 组织（必填） </el-col>
                  <el-col :span="5" class="col-style"> 岗位操作 </el-col>
                  <el-col :span="4" class="col-style"> 操作 </el-col>
                </el-row>
              </div>
              <div v-for="(val, index) in addForms.employees" :key="index">
                <el-row
                  v-if="index == 0"
                  style="width: 996px"
                  type="flex"
                  justify="space-between"
                >
                  <el-col :span="5" class="flex-col">
                    <el-form-item
                      label=""
                      :prop="'employees.' + index + '.phone'"
                      :rules="[
                        {
                          required: true,
                          validator: validatePhone,
                          trigger: 'blur',
                        },
                      ]"
                    >
                      <el-input
                        v-model="val.phone"
                        placeholder="请输入手机号"
                        size="small"
                        style="width: 180px"
                        :maxlength="11"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="5" class="flex-col">
                    <el-form-item
                      label=""
                      :prop="'employees.' + index + '.realName'"
                      :rules="{
                        required: true,
                        message: '姓名不能为空',
                        trigger: 'blur',
                      }"
                    >
                      <el-input
                        v-model="val.realName"
                        placeholder="请输入姓名"
                        size="small"
                        style="width: 180px"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="5" class="flex-col">
                    <el-form-item
                      label=""
                      :prop="'employees.' + 0 + '.deptIDList'"
                      :rules="{
                        required: true,
                        message: '请至少选择一个组织',
                        trigger: 'change',
                      }"
                    >
                      <el-cascader
                        style="width: 180px; margin-top: -2px"
                        size="small"
                        :placeholder="index == 0 ? '请选择组织' : '同上'"
                        v-model="val.deptIDList"
                        :options="orgList"
                        @change="selectOrgs(val.deptIDList)"
                        :props="{
                          value: 'id',
                          label: 'name',
                          checkStrictly: true,
                          emitPath: false,
                        }"
                      >
                        <template slot-scope="{ data }">
                          <span>{{ data.name }}</span>
                        </template>
                      </el-cascader>
                    </el-form-item>
                  </el-col>
                  <el-col :span="5" class="flex-col">
                    <el-form-item label="">
                      <el-cascader
                        style="width: 180px; margin-top: -2px"
                        size="small"
                        :placeholder="index == 0 ? '请选择岗位' : '同上'"
                        v-model="val.occIDList"
                        :options="queryOccList"
                        @change="selectOccs"
                        :props="{
                          value: 'id',
                          label: 'name',
                        }"
                      >
                        <template slot-scope="{ data }">
                          <span>{{ data.name }}</span>
                        </template>
                      </el-cascader>
                    </el-form-item>
                  </el-col>
                  <el-col
                    :span="4"
                    style="display: flex; justify-content: center"
                  >
                    <el-button
                      :disabled="index == 0"
                      type="text"
                      style="font-size: 12px; margin-top: -30px"
                      @click.prevent="removeUserFormsVal(val)"
                      >移除</el-button
                    >
                  </el-col>
                </el-row>
                <el-row
                  v-else
                  style="width: 996px"
                  type="flex"
                  justify="space-between"
                >
                  <el-col :span="5" class="flex-col">
                    <el-form-item
                      label=""
                      :prop="'employees.' + index + '.phone'"
                      :rules="[
                        {
                          required: true,
                          validator: validatePhoneS,
                          trigger: 'blur',
                        },
                      ]"
                    >
                      <el-input
                        v-model="val.phone"
                        placeholder="请输入手机号"
                        style="width: 180px"
                        size="small"
                        :maxlength="11"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="5" class="flex-col">
                    <el-form-item
                      label=""
                      :prop="'employees.' + index + '.realName'"
                      :rules="[
                        {
                          required: true,
                          validator: validateRealNameS,
                          trigger: 'blur',
                        },
                      ]"
                    >
                      <el-input
                        v-model="val.realName"
                        placeholder="请输入姓名"
                        style="width: 180px"
                        size="small"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="5" class="flex-col">
                    <el-form-item
                      label=""
                      :prop="'employees.' + 0 + '.deptIDList'"
                      :rules="[
                        {
                          required: true,
                          validator: validateDeptIDList,
                          trigger: 'change',
                        },
                      ]"
                    >
                      <el-cascader
                        size="small"
                        style="width: 180px; margin-top: -2px"
                        :placeholder="index == 0 ? '请选择组织' : '同上'"
                        v-model="val.deptIDList"
                        :options="orgList"
                        @change="selectOrgs(val.deptIDList)"
                        :props="{
                          value: 'id',
                          label: 'name',
                          checkStrictly: true,
                          emitPath: false,
                        }"
                      >
                        <template slot-scope="{ data }">
                          <span>{{ data.name }}</span>
                        </template>
                      </el-cascader>
                    </el-form-item>
                  </el-col>
                  <el-col :span="5" class="flex-col">
                    <el-form-item label="">
                      <el-cascader
                        size="small"
                        style="width: 180px; margin-top: -2px"
                        :placeholder="index == 0 ? '请选择岗位' : '同上'"
                        v-model="val.occIDList"
                        :options="queryOccList"
                        @change="selectOccs"
                        :props="{
                          value: 'id',
                          label: 'name',
                        }"
                      >
                        <template slot-scope="{ data }">
                          <span>{{ data.name }}</span>
                        </template>
                      </el-cascader>
                    </el-form-item>
                  </el-col>
                  <el-col
                    :span="4"
                    style="display: flex; justify-content: center"
                  >
                    <el-button
                      :disabled="index == 0"
                      type="text"
                      style="font-size: 12px; margin-top: -30px"
                      @click.prevent="removeUserFormsVal(val)"
                      >移除</el-button
                    >
                  </el-col>
                </el-row>
              </div>
              <el-form-item>
                <el-row>
                  <el-col :span="24">
                    <span
                      @click="addFormsVal()"
                      style="
                        color: #1e5aff;
                        display: block;
                        cursor: pointer;
                        margin-left: 10px;
                      "
                      ><i class="el-icon-circle-plus-outline"></i>
                      添加一条</span
                    >
                  </el-col>
                </el-row>
              </el-form-item>
            </el-form>

            <!-- 导入 -->
            <el-steps direction="vertical" :active="2" v-if="multiple == 3">
              <div>
                <el-step style="height: 140px; width: 550px">
                  <template slot="description">
                    <div style="color: #000">
                      下载用户信息导入模板，批量填写用户信息，每次最多可上传1万条数据
                    </div>
                    <el-button
                      type="primary"
                      size="mini"
                      @click="importTemplate()"
                      >下载模版
                    </el-button>
                  </template>
                </el-step>
                <el-step style="height: 140px; width: 550px">
                  <template slot="description">
                    <div style="color: #000">
                      上传填写好的用户信息表（仅限上传xls、xlsx格式）
                    </div>
                    <el-upload
                      ref="upload"
                      accept=".xlsx, .xls"
                      :headers="upload.headers"
                      action="#"
                      :on-preview="handlePreview"
                      :on-remove="handleRemove"
                      multiple
                      :limit="200"
                      :on-change="handleChange"
                      :on-exceed="handleExceed"
                      :file-list="fileList"
                      :auto-upload="false"
                      :http-request="uploadFile"
                    >
                      <el-button size="small" type="primary"
                        >选择文件</el-button
                      >
                    </el-upload>
                  </template>
                </el-step>
              </div>
            </el-steps>

            <!-- 用户导入对话框
            <el-dialog
              :title="upload.title"
              :visible.sync="upload.open"
              width="400px"
            >
              <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" />
                <div class="el-upload__text">
                  将文件拖到此处，或
                  <em>点击上传</em>
                </div>
                <div slot="tip" class="el-upload__tip">
                  <el-checkbox
                    v-model="upload.updateSupport"
                  />是否更新已经存在的用户数据
                  <el-link
                    type="info"
                    style="font-size: 12px"
                    @click="importTemplate"
                    >下载模板</el-link
                  >
                </div>
                <div slot="tip" class="el-upload__tip" style="color: red">
                  提示：仅允许导入“xls”或“xlsx”格式文件！
                </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> -->

            <!-- 编辑用户 -->
            <el-form
              :model="editEMP"
              v-if="multiple == 6"
              :rules="editEMPrules"
              ref="editEMP"
            >
              <el-form-item
                label="手机号"
                :label-width="formLabelWidth"
                required
                prop="phone"
              >
                <el-input
                  v-model.number="editEMP.phone"
                  placeholder="请输入手机号"
                  autocomplete="off"
                  class="input_width"
                  size="small"
                ></el-input>
              </el-form-item>
              <el-form-item
                label="密码"
                :label-width="formLabelWidth"
                prop="password"
              >
                <el-input
                  v-model="editEMP.password"
                  type="password"
                  autocomplete="off"
                  placeholder="必须包含字母、数字及特殊符号，且不小于8位"
                  class="input_width"
                  size="small"
                ></el-input>
              </el-form-item>
              <el-form-item
                label="姓名"
                :label-width="formLabelWidth"
                required
                prop="realName"
              >
                <el-input
                  v-model="editEMP.realName"
                  autocomplete="off"
                  placeholder="请输入姓名"
                  class="input_width"
                  size="small"
                ></el-input>
              </el-form-item>
              <el-form-item
                label="组织"
                :label-width="formLabelWidth"
                size="small"
                prop="deptIDList"
              >
                <el-cascader
                  v-model="editEMP.deptIDList"
                  :options="orgList"
                  @change="editSelectOrg"
                  :props="{
                    value: 'id',
                    label: 'name',
                    checkStrictly: true,
                    emitPath: false,
                  }"
                >
                  <template slot-scope="{ data }">
                    <span>{{ data.name }}</span>
                  </template>
                </el-cascader>
              </el-form-item>
              <el-form-item
                :label-width="formLabelWidth"
                v-for="item in editEMP.deptIDLists"
                :key="item.id"
                size="small"
                prop="orgs"
              >
                <el-cascader
                  v-model="item.deptIDItem"
                  :options="orgList"
                  :props="{
                    value: 'id',
                    label: 'name',
                    checkStrictly: true,
                    emitPath: false,
                  }"
                  @change="handleSelectOrgs"
                >
                </el-cascader>
                <el-button plain @click="editDelItemOrgs(item)" class="ml0"
                  >删除</el-button
                >
              </el-form-item>
              <el-form-item
                label=""
                :label-width="formLabelWidth"
                style="margin-top: -26px"
              >
                <i
                  class="el-icon-circle-plus-outline"
                  style="font-size: 16px; color: #1e5aff"
                >
                </i>
                <el-button
                  type="text"
                  @click="editAddUserFormOrg()"
                  size="mini"
                  style="margin-left: -6px"
                  >添加</el-button
                >
              </el-form-item>
              <el-form-item
                label="岗位"
                :label-width="formLabelWidth"
                style="font-weight: bold"
              >
                <el-cascader
                  size="small"
                  style="width: 200px; margin-top: -2px"
                  placeholder="请选择岗位"
                  v-model="editEMP.occIDList"
                  :options="queryOccList"
                  @change="editSelectOcc"
                  :props="{
                    value: 'id',
                    label: 'name',
                  }"
                >
                  <template slot-scope="{ data }">
                    <span>{{ data.name }}</span>
                  </template>
                </el-cascader>
              </el-form-item>
              <el-form-item
                :label-width="formLabelWidth"
                v-for="(item, index) in editEMP.occIDLists"
                :key="index"
                size="small"
              >
                <el-cascader
                  v-model="item.occIDItem"
                  :props="{
                    value: 'id',
                    label: 'name',
                  }"
                  :options="queryOccList"
                  @change="editSelectOccS"
                ></el-cascader>
                <el-button plain @click="editDelItemOccs(item)" class="ml0"
                  >删除</el-button
                >
              </el-form-item>
              <el-form-item
                label=""
                :label-width="formLabelWidth"
                style="margin-top: -26px"
              >
                <i
                  class="el-icon-circle-plus-outline"
                  style="font-size: 16px; color: #1e5aff"
                ></i>
                <el-button
                  type="text"
                  @click="editAddUserFormOcc()"
                  size="mini"
                  style="margin-left: -6px"
                  >添加</el-button
                >
              </el-form-item>

              <el-form-item
                label="邮箱"
                :label-width="formLabelWidth"
                prop="email"
              >
                <el-input
                  v-model="employees.email"
                  autocomplete="off"
                  placeholder="请输入邮箱"
                  class="input_width"
                  size="small"
                ></el-input>
              </el-form-item>
            </el-form>
          </div>
          <!-- 设置岗位 -->
          <el-form :model="occList" v-if="multiple == 4">
            <!-- <div v-for="(item, index) in occList.idList" :key="index"> -->
            <div v-for="(item, index) in occList.list" :key="index">
              <el-form-item
                :label="index == 0 ? '岗位' : ''"
                :label-width="formLabelWidth"
                style="font-weight: bold"
                :prop="'list.' + index + '.id'"
              >
                <el-cascader
                  size="small"
                  style="width: 200px; margin-top: -2px"
                  placeholder="请选择岗位"
                  v-model="item.id"
                  :options="queryOccList"
                  @change="chargeSelectOcc(item.id)"
                  :props="{
                    value: 'id',
                    label: 'name',
                  }"
                >
                  <template slot-scope="{ data }">
                    <span>{{ data.name }}</span>
                  </template>
                </el-cascader>
                <el-button
                  plain
                  v-if="index != 0"
                  @click="delItemOcc(item)"
                  class="ml0"
                  >删除</el-button
                >
              </el-form-item>
            </div>
            <el-form-item label="" :label-width="formLabelWidth">
              <i
                class="el-icon-circle-plus-outline"
                style="font-size: 16px; color: #409eff"
              ></i
              ><el-button type="text" @click="addItemOcc()">
                添加一条
              </el-button>
            </el-form-item>
          </el-form>

          <!-- 添加用户穿梭框 -->
          <div class="chooseBox" v-if="multiple == 5">
            <div class="dialog_box">
              <el-row :gutter="10">
                <el-col :span="12">
                  <h3>选择:</h3>
                  <div class="side_left">
                    <div class="mb10">
                      <el-input
                        prefix-icon="el-icon-search"
                        v-model="filterObj.filter"
                        placeholder="输入关键字搜索"
                        clearable
                        @keyup.enter.native="searchManager()"
                      ></el-input>
                    </div>
                    <div class="mb10">
                      <el-breadcrumb class="breadcrumb" separator="/">
                        <el-breadcrumb-item
                          style="cursor: pointer"
                          @click.native="breadcrumbAll"
                        >
                          一级组织
                        </el-breadcrumb-item>
                        <el-breadcrumb-item
                          v-for="(item, index) in breadArr"
                          :key="index"
                          style="cursor: pointer"
                          @click.native="breadcrumb(item)"
                        >
                          {{ item.name }}
                        </el-breadcrumb-item>
                      </el-breadcrumb>
                    </div>
                    <div class="leftData mb10">
                      <div>
                        <el-checkbox
                          :indeterminate="isIndeterminate"
                          v-model="allChecked"
                          @change="handleCheckAllChange"
                          >全选</el-checkbox
                        >
                      </div>
                      <ul v-if="root.children != null" class="over-y">
                        <li
                          class="flexLeft"
                          v-for="(v, k) in root.children"
                          :key="k"
                        >
                          <div>
                            <el-checkbox-group v-model="orgCheckList">
                              <el-checkbox
                                :key="v.id"
                                :label="v.id"
                                @change="(val) => selectORG(val, v)"
                              >
                                <div></div>
                              </el-checkbox>
                            </el-checkbox-group>
                          </div>
                          <div @click="showLower(v)">
                            {{ v.name }}
                          </div>
                        </li>
                      </ul>
                    </div>
                  </div>
                </el-col>
                <el-col :span="12">
                  <h3>己选:</h3>
                  <div class="side_right">
                    <ul
                      v-if="toData.length != 0"
                      style="height: 300px; overflow-y: auto"
                    >
                      <li v-for="n in toData" :key="n.id" class="flexDiv">
                        <div class="userlist">
                          <div>{{ n.name }}</div>
                          <div @click="removeUser(n.id)">
                            <i class="el-icon-error"></i>
                          </div>
                        </div>
                      </li>
                    </ul>
                  </div>
                </el-col>
              </el-row>
            </div>
          </div>

          <div
            v-if="multiple == 1"
            slot="footer"
            class="dialog-footer"
            style="padding-top: 0"
          >
            <el-button type="primary" @click="submitForm" size="mini"
              >确 定</el-button
            >
            <el-button @click="resetForm('employee')" size="mini"
              >取 消</el-button
            >
          </div>
          <div v-if="multiple == 2" slot="footer" class="dialog-footer pt5">
            <el-button type="primary" @click="submitForms()" size="mini"
              >确 定</el-button
            >
            <el-button @click="clearDialog()" size="mini">取 消</el-button>
          </div>
          <div v-if="multiple == 4" slot="footer" class="dialog-footer pt5">
            <el-button type="primary" @click="confirmSetOcc()" size="mini"
              >确 定</el-button
            >
            <el-button @click="clearDialog()" size="mini">取 消</el-button>
          </div>
          <div v-if="multiple == 6" slot="footer" class="dialog-footer pt5">
            <el-button type="primary" @click="clickEditEMP()" size="mini"
              >确 定</el-button
            >
            <el-button @click="resetForm('editEMP')" size="mini"
              >取 消</el-button
            >
          </div>
          <div v-if="multiple == 5" slot="footer" class="dialog-footer pt5">
            <el-button type="primary" @click="clickSetOrg()" size="mini"
              >确 定</el-button
            >
            <el-button @click="clearDialog()" size="mini">取 消</el-button>
          </div>
          <div v-if="multiple == 3" slot="footer" class="dialog-footer pt5">
            <el-button type="primary" @click="submitUpload()" size="mini"
              >确 定</el-button
            >
            <el-button @click="clearDialog()" size="mini">取 消</el-button>
          </div>
        </el-dialog>
      </el-card>
    </template>
  </BasicLayout>
</template>

<script>
import { listJobs, listDepartments, listUser } from "@/api/jobs";
import { listUsers } from "@/api/org";
import {
  employeeBatch,
  delUser,
  delJobs,
  getOccInfo,
  editUserInfo,
  editUserOcc,
  userTemplate, //下载模板
} from "@/api/occ";
import { getToken } from "@/utils/auth";

export default {
  data() {
    var validatePhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("手机号不能为空"));
      } else {
        const reg = /^1[3|4|5|6|7|8|9][0-9]\d{8}$/;
        if (reg.test(value)) {
          callback();
        } else {
          return callback(new Error("请输入正确的手机号"));
        }
      }
    };
    var validatePass = (rule, value, callback) => {
      if (!value) {
        callback();
      } else {
        const passwordReg = /(?=.*[a-z])(?=.*[^a-z0-9]).{8,12}/;
        const isValid = passwordReg.test(value);
        if (!isValid) {
          return callback(
            new Error("必须包含字母、数字及特殊符号，且不小于8位")
          );
        } else {
          callback();
        }
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (this.employees.password == "") {
        callback();
      } else if (value !== this.employees.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    var validateEmail = (rule, value, callback) => {
      if (value) {
        const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
        if (mailReg.test(value)) {
          callback();
        } else {
          callback(new Error("请输入正确的邮箱格式"));
        }
      } else {
        callback();
      }
    };
    var validateEditPw = (rule, value, callback) => {
      if (!value) {
        callback();
      } else {
        const passwordReg = /(?=.*[a-z])(?=.*[^a-z0-9]).{8,12}/;
        const isValid = passwordReg.test(value);
        if (!isValid) {
          return callback(
            new Error("必须包含字母、数字及特殊符号，且不小于8位")
          );
        } else {
          callback();
        }
      }
    };
    return {
      parentName: "",
      filterObj: {},
      //存储上传的文件
      fileList: [],
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址 http://192.168.31.230:6209/api/v3/employees/batch/import
        url: process.env.VUE_APP_BASE_API + "/api/v3/employees/batch/import",
      },
      toData: [],
      orgCheckList: [],
      root: {},
      isIndeterminate: true,
      //选中用户列表
      checkedList: [],
      breadArr: [],
      pageIndex: 1,
      // 总条数
      total: 0,
      // 组织列表
      orgList: [],
      queryOccList: [],
      // 设置岗位
      occList: {
        list: [
          {
            id: "",
          },
        ],
        selectList: [],
        idList: [],
      },
      //弹窗宽度
      width: "890px",
      // 批量添加用户
      addForms: {
        employees: [
          {
            phone: "",
            realName: "",
            deptIDList: "",
            occIDList: [],
          },
        ],
      },
      addUser: {
        phone: [{ required: true, validator: validatePhone, trigger: "blur" }],
        password: [{ validator: validatePass, trigger: "blur" }],
        confirm: [{ validator: validatePass2, trigger: "blur" }],
        realName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        deptIDList: [
          { required: true, message: "请至少选择一个组织", trigger: "change" },
        ],
        email: [{ validator: validateEmail, trigger: "blur" }],
      },
      editEMPrules: {
        phone: [{ validator: validatePhone, trigger: "blur" }],
        password: [{ validator: validateEditPw, trigger: "blur" }],
        realName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        deptIDList: [
          { required: true, message: "请至少选择一个组织", trigger: "change" },
        ],
        email: [{ validator: validateEmail, trigger: "blur" }],
      },
      //关联用户弹出层
      assOpen: false,
      // 查询参数
      queryParams: {
        filter: "",
        sortBy: "id",
        offset: 0,
        limit: 10,
        occID: "",
        deptID: "",
        order: "desc",
        deptIDList: [],
      },
      //穿梭框模式
      mode: "transfer",
      allChecked: false, // 设置组织全选
      isDisabled: true,
      multiple: 0, // 1 单个添加新用户  2 批量添加新用户 3 导入  5批量设置岗位
      title: "",
      tableUser: [],
      // 批量删除信息
      multipleSelection: [],
      loading: false,
      dialogVisible: false,
      employees: {
        phone: "",
        password: "",
        confirm: "",
        realName: "",
        deptIDList: [],
        deptIDLists: [],
        deptTotalList: [],
        occIDList: [],
        occIDLists: [],
        occTotalList: [],
        email: "",
      },
      editEMP: {
        id: "",
        phone: "",
        password: "",
        realName: "",
        deptIDList: [],
        deptIDLists: [],
        deptTotalList: [],
        occIDList: [],
        occIDLists: [],
        occTotalList: [],
        email: "",
      },
      formLabelWidth: "120px",
      index: 0, // 批量添加监听数组下标
      deptID: "",
    };
  },
  created() {
    this.getListJobs();
    this.getListUsers();
    this.getListOrg();
  },
  methods: {
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.dialogVisible = false;
      this.multiple = 0;
    },
    searchManager() {
      let data = {
        filter: this.filterObj.filter,
        sortBy: "id",
        offset: 0,
        limit: 10,
        occID: "",
        deptID: this.deptID,
        order: "desc",
      };
      listUser(data).then((res) => {});
    },
    editSelectOcc() {},
    editSelectOccS() {},
    /** 排序回调函数 */
    handleSortChang(column, prop, order) {
      prop = column.prop;
      order = column.order;
      this.queryParams.orderBy = prop;
      if (order === "descending") {
        this.queryParams.order = "desc";
      } else if (order === "ascending") {
        this.queryParams.order = "asc";
      } else {
        this.queryParams.order = "desc";
      }
      this.getListUsers();
    },
    //上传文件
    submitUpload() {
      const loading = this.$loading({
        lock: true,
        text: "数据提取中，请稍后",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      if (this.fileList.length === 0) {
        this.$message({
          message: "请先选择文件",
          type: "warning",
        });
      } else {
        const isLt700K = this.fileList.every(
          (file) => file.size / 1024 / 1024 / 1024 < 700
        );
        if (!isLt700K) {
          this.$message.error("请检查，上传文件大小不能超过700KB!");
        } else {
          var formData = new FormData(); //  用FormData存放上传文件
          this.fileList.forEach((file) => {
            formData.append("file", file.raw, file.raw.name);
          });
          //向webapi发起请求，等待后台接收
          this.$axios
            .post(this.upload.url, formData, {
              headers: {
                "Content-Type": "multipart/form-data",
              },
            })
            .then(
              (response) => {
                if (response.status == "200") {
                  setTimeout(() => {
                    loading.close();
                    this.getListUsers();
                    this.$message({
                      type: "success",
                      message: "导入成功!",
                    });
                    this.fileList = [];
                    this.fileData = "";
                    this.dialogVisible = false;
                    this.isLoading = false;
                  }, 1000);
                } else {
                  this.$message({
                    type: "error",
                    message: "导入失败，请检查模板是否正确",
                  });
                  this.isLoading = false;
                }
              },
              (error) => {
                loading.close();
                this.$message.error("系统异常，请稍后再试");
                return Promise.reject(error);
              }
            );
        }
      }
    },
    uploadFile(file) {
      this.fileData.append("files", file.file);
    },
    handleChange(file, fileList) {
      let existFile = fileList
        .slice(0, fileList.length - 1)
        .find((f) => f.name === file.name);
      if (existFile) {
        this.$message.error("当前文件已经存在!");
        fileList.pop();
      }
      this.fileList = fileList;
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.fileList = fileList;
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择200个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    /** 下载模板操作 */
    importTemplate() {
      userTemplate().then((response) => {
        let url = window.URL.createObjectURL(new Blob([response]));
        let link = document.createElement("a");
        link.style.display = "none";
        link.href = url;
        link.setAttribute("download", "员工模版.xlsx");
        document.body.appendChild(link);
        link.click();
      });
    },
    // 文件上传中处理
    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(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    clearDialog() {
      // this.isDisabled = true;
      this.dialogVisible = false;
      if (this.multiple == 1) {
        this.employees = {};
      } else if (this.multiple == 2) {
        this.addForms = {};
      } else if (this.multiple == 3) {
        this.addForms = {};
      } else if (this.multiple == 4) {
        this.isDisabled = !this.multipleSelection.length;
        this.occList = {};
      } else if (this.multiple == 5) {
        this.isDisabled = !this.multipleSelection.length;
        this.toData = [];
        this.orgCheckList = [];
      } else if (this.multiple == 6) {
        this.editEMP = {};
      }
    },

    clickSetOrg() {
      let list = this.multipleSelection.map((val) => {
        return val.id;
      });
      let data = {
        employeeIDList: list,
        deptIDList: this.orgCheckList,
      };
      editUserOcc(JSON.stringify(data)).then((res) => {
        if (res.code == 0) {
          this.resetQuery();
          this.dialogVisible = false;
          this.multiple = 0;
          this.toData = [];
          this.orgCheckList = [];
          this.$message({
            type: "success",
            message: "设置成功!",
          });
        }
      });
    },

    selectORG(val, index) {
      if (val === true) {
        this.toData.push(index);
        if (this.toData.length != 0) {
          let deWeightThree = () => {
            let map = new Map();
            for (let item of this.toData) {
              if (!map.has(item.id)) {
                map.set(item.id, item);
              }
            }
            return [...map.values()];
          };
          this.toData = deWeightThree();
        }
      } else {
        this.deleteItem(index.id, this.toData);
      }
    },
    deleteItem(item, list) {
      for (var key in list) {
        if (list[key].id === item) {
          list.splice(key, 1);
        }
      }
    },
    //点击下级
    showLower(item) {
      if (item.children == null) {
        this.msgWarning("该部门下暂无人员");
      }
      this.deptID = item.id;
      this.root.children = item.children;
      this.isIndeterminate = true;
      this.allChecked = false;
      this.breadArr;
      var index = this.breadArr.indexOf(item);
      if (index == -1) {
        this.breadArr.push(item);
      }
    },
    // 全选
    handleCheckAllChange(val) {
      this.isIndeterminate = false;
      if (val == true) {
        if (this.toData.length != 0) {
          this.toData = this.toData.concat(this.root.children);

          let deWeightThree = () => {
            let map = new Map();
            for (let item of this.toData) {
              if (!map.has(item.id)) {
                map.set(item.id, item);
              }
            }
            return [...map.values()];
          };
          this.toData = deWeightThree();
          this.orgCheckList = this.toData.map((i) => {
            return i.id;
          });
        } else {
          this.toData = this.root.children;
          this.orgCheckList = this.toData.map((i) => {
            return i.id;
          });
        }
      } else {
        if (this.toData.length != 0) {
          this.toData = this.toData.filter(
            (x) => !this.root.children.some((item) => x.id === item.id)
          );
          this.orgCheckList = this.toData.map((i) => {
            return i.id;
          });
        } else {
          this.toData = this.root.children;
          this.orgCheckList = this.toData.map((i) => {
            return i.id;
          });
        }
      }
    },
    //右侧移除用户
    removeUser(id) {
      this.allChecked = false;
      this.toData = this.toData.filter((item) => {
        return item.id != id;
      });
      this.orgCheckList = this.orgCheckList.filter((item) => {
        return item != id;
      });
    },
    breadcrumbAll() {
      //获取全部组件数据
      this.getListOrg();
      this.breadArr = [];
    },
    //关联用户弹窗，点击面包屑导航
    breadcrumb(item) {
      if (item.children != null) {
        this.root.children = item.children;
        var index = this.breadArr.indexOf(item);
        if (index !== -1) {
          this.breadArr.splice(index + 1);
        }
      }
    },
    delItemOcc(item) {
      var index = this.occList.list.indexOf(item);
      if (index !== -1) {
        this.occList.list.splice(index, 1);
      }
    },
    editSelectOrg(value) {
      console.log(value, "编辑");
    },
    /**编辑用户确定按钮 */
    clickEditEMP() {
      this.$refs["editEMP"].validate((valid) => {
        if (valid) {
          console.log(this.editEMP.deptIDList);
          if (this.editEMP.deptIDList.length > 0) {
            console.log(this.editEMP.deptIDList);
            this.editEMP.deptTotalList = this.editEMP.deptIDList.slice(-1);
            console.log(this.editEMP.deptTotalList);
          } else {
            this.editEMP.deptTotalList.push(this.editEMP.deptIDList);
            console.log(this.editEMP.deptTotalList);
          }
          if (this.editEMP.deptIDLists.length > 0) {
            this.editEMP.deptIDLists.forEach((val, index) => {
              if (val.deptIDItem.length > 1) {
                this.editEMP.deptTotalList.push(
                  Number(val.deptIDItem.slice(-1))
                );
              } else if (
                val.deptIDItem.length > 0 &&
                val.deptIDItem.length == 1
              ) {
                this.editEMP.deptTotalList.push(val.deptIDItem[0]);
              } else {
                this.editEMP.deptTotalList.push(val.deptIDItem);
              }
            });
          }
          if (this.editEMP.occIDLists.length > 0) {
            this.editEMP.occIDLists.forEach((val, index) => {
              if (val.occIDItem != "") {
                let strId = val.occIDItem.toString();
                this.editEMP.occTotalList.push(strId);
              }
              this.editEMP.occTotalList = this.editEMP.occTotalList.map(Number);
            });
          }
          let deptArray = this.editEMP.deptTotalList;
          let occArray = [
            ...this.editEMP.occIDList,
            ...this.editEMP.occTotalList,
          ];
          this.editEMP.occIDList = this.editEMP.occIDList.concat(
            this.editEMP.occTotalList
          );
          let data = {
            deptIDList: deptArray,
            email: this.editEMP.email,
            realName: this.editEMP.realName,
            password: this.editEMP.password,
            occIDList: occArray,
            phone: this.editEMP.phone.toString(),
          };
          editUserInfo(JSON.stringify(data), this.editEMP.id).then((res) => {
            if (res.code && res.code != 0) {
              this.msgError(res.msg);
            } else {
              this.getListUsers();
              this.dialogVisible = false;
              this.multiple = 0;
              this.msgSuccess("更改成功");
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    editAddUserFormOrg() {
      this.editEMP.deptIDLists.push({
        deptIDItem: [],
      });
    },
    editAddUserFormOcc() {
      this.editEMP.occIDLists.push({
        occIDItem: "",
      });
    },
    /**设置岗位选择 */
    chargeSelectOcc(index) {
      console.log(index);
    },
    /**批量设置岗位确定 */
    confirmSetOcc() {
      let list = this.occList.list.map((val, index) => {
        return val.id;
      });
      this.occList.selectList = this.occList.selectList.concat(...list);
      let data = {
        employeeIDList: this.occList.idList,
        occupationIDList: this.occList.selectList,
      };
      editUserOcc(JSON.stringify(data)).then((res) => {
        if (res.code == 0) {
          this.dialogVisible = false;
          this.occList.idList = [];
          this.occList.selectList = [];
          this.occList.list = [];
          this.multiple = 0;
          this.msgSuccess("设置成功!");
          this.getListUsers();
        } else {
          this.msgError("修改失败");
        }
      });
    },
    /**批量删除员工 */
    handleDelUsers() {
      this.$confirm(
        "批量删除以后所选用户将不能再登录该平台, 是否删除?",
        "删除",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        let valueArray = [];
        valueArray = this.multipleSelection.map((val, index) => {
          return val.id;
        });
        let data = {
          employeeID: valueArray.toString(),
        };
        delJobs(data).then((res) => {
          this.resetQuery();
          this.msgSuccess("删除成功!");
        });
      });
    },
    // 重置table
    resetQuery() {
      this.pageIndex = 1;
      this.total = 0;
      this.queryParams = {
        filter: "",
        sort_by: "id",
        offset: 0,
        limit: 10,
        occID: "",
        deptID: "",
        order: "desc",
      };
      this.getListUsers();
    },
    // 关键字搜索
    filterQuery(value) {
      // this.queryParams.filter = value;
      this.pageIndex = 1;
      this.queryParams.offset = (this.pageIndex - 1) * this.queryParams.limit;
      this.getListUsers();
    },
    /**选择组织查询 */
    querySelectOrg(value) {
      console.log(value, "value");
      this.isEdit = false;
      if (value != undefined) {
        this.queryParams.deptID = value;
      } else {
        this.queryParams.deptID = "";
      }
      this.getListUsers();
    },
    validateDeptIDList(rule, value, callback) {
      if (value) {
        callback();
      } else {
        callback(new Error("组织不可为空"));
      }
    },
    validateRealNameS(rule, value, callback) {
      this.index = rule.field.slice(10, 11);
      if (!value) {
        if (this.addForms.employees[this.index].phone !== "") {
          callback(new Error("请输入姓名"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    },
    validatePhone(rule, value, callback) {
      if (!value) {
        return callback(new Error("手机号不能为空"));
      } else {
        const reg = /^1[3|4|5|6|7|8|9][0-9]\d{8}$/;
        if (reg.test(value)) {
          callback();
        } else {
          return callback(new Error("请输入正确的手机号"));
        }
      }
    },
    validatePhoneS(rule, value, callback) {
      this.index = rule.field.slice(10, 11);
      if (!value) {
        if (this.addForms.employees[this.index].realName !== "") {
          callback(new Error("请输入手机号"));
        } else {
          callback();
        }
      } else {
        const reg = /^1[3|4|5|6|7|8|9][0-9]\d{8}$/;
        if (reg.test(value)) {
          callback();
        } else {
          return callback(new Error("请输入正确的手机号"));
        }
      }
    },
    /**添加批量用户 */
    submitForms() {
      this.$refs["employees"].validate((valid) => {
        if (valid) {
          let data = this.addForms.employees;
          let dataValue = {
            employees: [],
          };
          console.log(data, "data");
          dataValue.employees = data
            .map((val, index) => {
              if (val.realName !== "" && val.phone !== "") {
                if (
                  val.realName !== "" &&
                  val.phone !== "" &&
                  val.deptIDList == ""
                ) {
                  val.deptIDList = this.addForms.employees[0].deptIDList;
                  console.log(val.deptIDList);
                } else {
                  // let arr = []
                  // val.deptIDList = arr.push(val.deptIDList)
                  // console.log(arr)
                  val.deptIDList = [val.deptIDList];
                }
                if (
                  val.realName !== "" &&
                  val.phone !== "" &&
                  val.occIDList.length == 0
                ) {
                  val.occIDList =
                    this.addForms.employees[0].occIDList.slice(-1);
                } else {
                  val.occIDList = val.occIDList.slice(-1);
                }
                return val;
              }
            })
            .filter((val, index) => {
              return val !== undefined;
            });

          employeeBatch(JSON.stringify(dataValue)).then((res) => {
            if (res.code && res.code != 0) {
              this.msgError(res.msg);
            } else {
              this.getListUsers();
              this.dialogVisible = false;
              this.multiple = 0;
            }
          });
        }
      });
    },
    /**批量选择组织 */
    selectOrgs(index) {
      console.log(index, "......////");
    },
    /**批量选择组织 */
    selectOccs() {},
    /**获取用户table列表 */
    getListUsers() {
      this.queryParams.offset = (this.pageIndex - 1) * this.queryParams.limit;
      listUsers(this.queryParams).then((res) => {
        this.tableUser = res.employees;
        this.total = res.total;
        this.loading = false;
      });
    },
    /**获取组织 */
    getListOrg() {
      listDepartments().then((res) => {
        this.orgList = res.root.children;
        this.root = res.root;
        this.parentName = res.root.name;
      });
    },
    /**选择岗位 */
    getBlurValue(value) {
      this.queryParams.occID = value;
      this.getListUsers();
    },
    /**获取岗位 */
    getListJobs() {
      let occupations = {
        orderBy: "createdTime",
        sort: "desc",
        offset: 0,
        limit: 5000,
        filter: "",
      };
      listJobs(occupations).then((res) => {
        this.queryOccList = res.occupationItems;
      });
    },
    /**添加选择设置岗位 */
    addItemOcc() {
      this.occList.list.push({
        id: "",
      });
    },
    /**选择设置岗位 */
    setHandleItemOcc(value) {
      // setUserOcc
    },
    /**设置岗位 */
    setOcc() {
      this.dialogVisible = true;
      this.title = "设置岗位";
      this.multiple = 4;
      this.width = "890px";
      this.occList.list = [
        {
          id: "",
        },
      ];
      this.occList.idList = this.multipleSelection.map((val) => {
        return val.id;
      });
      if (this.multipleSelection.length == 1) {
        getOccInfo(this.multipleSelection[0].id).then((res) => {
          if (res.occupationList != null) {
            this.occList.list = res.occupationList;
          }
        });
      }
      // if (this.multipleSelection.length > 0) {
      //   this.multipleSelection.forEach((val, index) => {
      //     this.occList.idList.push(val.id);
      //   });
      // }
    },
    /**移除批量添加item */
    removeUserFormsVal(item) {
      var index = this.addForms.employees.indexOf(item);
      if (index !== -1) {
        this.addForms.employees.splice(index, 1);
      }
    },
    /**批量添加item */
    addFormsVal() {
      this.addForms.employees.push({
        phone: "",
        realName: "",
        deptIDList: "",
        occIDList: [],
      });
    },
    /**按钮确定 */
    submitForm() {
      this.$refs["employee"].validate((valid) => {
        if (valid) {
          this.employees.deptTotalList.push(this.employees.deptIDList);
          if (this.employees.deptIDLists.length > 0) {
            this.employees.deptIDLists.forEach((val, index) => {
              if (val.deptIDItem != "") {
                let strId = val.deptIDItem;
                this.employees.deptTotalList.push(strId);
              }
            });
          }
          if (this.employees.occIDLists.length > 0) {
            this.employees.occIDLists.forEach((val, index) => {
              if (val.occIDItem != "") {
                let strId = val.occIDItem.toString();
                this.employees.occTotalList.push(strId);
              }
              this.employees.occTotalList =
                this.employees.occTotalList.map(Number);
            });
          }
          let deptArray = this.employees.deptTotalList;
          let occArray = [
            ...this.employees.occIDList,
            ...this.employees.occTotalList,
          ];
          let data = {
            employees: [
              {
                deptIDList: deptArray,
                email: this.employees.email,
                password: this.employees.password,
                realName: this.employees.realName,
                occIDList: occArray,
                phone: this.employees.phone.toString(),
              },
            ],
          };
          employeeBatch(JSON.stringify(data)).then((res) => {
            if (res.code && res.code != 0) {
              this.msgError(res.msg);
            } else {
              this.msgSuccess("添加成功！");
              this.getListUsers();
              this.dialogVisible = false;
              this.multiple = 0;
              this.$refs["employee"].resetFields();
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    /**选择多个岗位 */
    handleSelectOccS(index) {},
    /**选择第一个岗位 */
    handleSelectOcc(index) {},
    /**选择多个组织 */
    handleSelectOrgs(index) {
      console.log(index, "编辑机");
    },
    /**选择第一个组织 */
    handleSelectOrg(value) {},

    /* 编辑删除组织 */
    editDelItemOrgs(item) {
      var index = this.editEMP.deptIDLists.indexOf(item);
      if (index !== -1) {
        this.editEMP.deptIDLists.splice(index, 1);
      }
    },
    /**删除添加某个子岗位 */
    editDelItemOccs(item) {
      var index = this.editEMP.occIDLists.indexOf(item);
      if (index !== -1) {
        this.editEMP.occIDLists.splice(index, 1);
      }
    },
    /**删除添加某个子岗位 */
    delItemOccs(item) {
      var index = this.employees.occIDLists.indexOf(item);
      if (index !== -1) {
        this.employees.occIDLists.splice(index, 1);
      }
    },
    /*添加岗位*/
    addUserFormOcc() {
      this.employees.occIDLists.push({
        occIDItem: "",
      });
    },
    /**删除添加某个子组织 */
    delItemOrgs(item) {
      var index = this.employees.deptIDLists.indexOf(item);
      if (index !== -1) {
        this.employees.deptIDLists.splice(index, 1);
      }
    },
    /*添加组织*/
    addUserFormOrg() {
      this.employees.deptIDLists.push({
        deptIDItem: "",
      });
    },
    /**设置组织 */
    setOrgs() {
      this.dialogVisible = true;
      this.multiple = 5;
      this.title = "设置组织";
      this.width = "890px";
    },
    /**删除当前用户 */
    delRow(index) {
      this.$confirm("删除以后所选用户将不能再登录该平台, 是否删除?", "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delUser(index.id).then((res) => {
            this.resetQuery();
            this.msgSuccess("删除成功!");
          });
        })
        .catch((err) => {
          console.log(err);
        });
    },
    /**编辑当前用户 */
    editRow(index) {
      let depaList = [];
      let occList = [];
      getOccInfo(index.id).then((res) => {
        this.editEMP.phone = res.phone;
        this.editEMP.realName = res.name;
        this.editEMP.email = res.email;
        this.editEMP.id = res.id;
        this.editEMP.realName = res.name;
        this.editEMP.occIDList = [];
        this.editEMP.deptIDList = [];
        this.editEMP.deptIDLists = [];
        this.editEMP.deptTotalList = [];
        this.editEMP.occIDLists = [];
        this.editEMP.occTotalList = [];
        if (res.occupationList != null) {
          occList = res.occupationList;
          this.editEMP.occIDList.push(occList[0].id);
        }
        if (res.departmentList != null) {
          depaList = res.departmentList;
        }
        depaList.map((val, index) => {
          return val.parentIdList.push(val.id);
        });
        if (depaList.length > 0) {
          this.editEMP.deptIDList = depaList[0].parentIdList;
        }
        if (depaList.length > 1) {
          let depaLists = depaList.shift();
          for (let i = 0; i < depaList.length; i++) {
            this.editEMP.deptIDLists[i] = Object.assign(
              {},
              this.editEMP.deptIDLists[i],
              { deptIDItem: depaList[i].parentIdList }
            );
          }
        }
        if (occList.length > 1) {
          let occLists = occList.shift();
          for (let i = 0; i < occList.length; i++) {
            this.editEMP.occIDLists[i] = Object.assign(
              {},
              this.editEMP.occIDLists[i],
              { occIDItem: occList[i].id }
            );
          }
        }
      });
      this.title = "编辑用户";
      this.dialogVisible = true;
      this.multiple = 6;
      // this.$nextTick(this.$refs["editEMP"].validate);
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.isDisabled = !val.length;
      // this.isDisabled = false;
      this.multipleSelection = val;
    },

    /** 添加用户 */
    userAdd(command) {
      this.dialogVisible = true;
      if (command == "1") {
        this.title = "添加用户";
        this.multiple = 1;
        this.width = "890px";
        this.employees = {
          phone: "",
          password: "",
          confirm: "",
          realName: "",
          deptIDList: [],
          deptIDLists: [],
          deptTotalList: [],
          occIDList: [],
          occIDLists: [],
          occTotalList: [],
          email: "",
        };
      } else {
        this.title = "批量添加用户";
        this.multiple = 2;
        this.width = "1060px";
        this.addForms = {
          employees: [
            {
              phone: "",
              realName: "",
              deptIDList: "",
              occIDList: [],
            },
          ],
        };
        // this.$refs.employees.resetFields();
      }
    },
    openImport() {
      this.title = "导入";
      this.multiple = 3;
      this.dialogVisible = true;
      this.upload.open = true;
    },
    selectionChange(selection) {},
    /** 修改每行input  */
    inputChange(value) {},
    handleSizeChange(current) {},
    handleCurrentChange(current) {},
  },
};
</script>

<style lang="scss" scoped>
.el-form-item {
  margin-bottom: 32px !important;
}
.el-breadcrumb {
  line-height: 1.8;
}
@import "~@/styles/variables.scss";
.over-y {
  overflow-y: auto;
  height: 210px;
}
.flex-col {
  display: flex;
  justify-content: center;
  align-items: center;
}
.col-style {
  text-align: center;
  margin: 0;
  font-size: 14px;
  font-family: PingFangSC-Medium;
  line-height: 22px;
  color: #000;
}
.addForms {
  width: 1200px;
}
.center-box {
  width: 636px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e9e9e9;
  margin-bottom: 32px;
  .dialog-tip {
    font-size: 16px;
    font-family: PingFang SC;
    font-weight: 500;
    line-height: 24px;
    color: rgba(0, 0, 0, 0.85);
  }
}
.org_header {
  border-bottom: 1px solid #dcdfe6;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 32px;
  margin-left: -32px;
  margin-right: -32px;
  margin-top: -26px;
}
.subject {
  color: $titleBlue;
  font-weight: bold;
}
.header_btn_box {
  padding: 10px 0 10px;
  display: flex;
}
.el-flex {
  background-color: #fff;
}
.selectOrg {
  display: flex;
}
.input_width {
  width: 468px;
}
.select_width {
  width: 136px;
}
.chooseBox ::v-deep .el-dialog__body {
  padding: 10px 20px !important;
}
::v-deep .el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 192px;
}
::v-deep .dialog-footer {
  text-align: center;
}
.side_left,
.side_right {
  background: #f2f6fc;
  padding: 15px;
  height: 350px;
}
.side_right {
  overflow-y: scroll;
}

.flexDiv {
  width: 100%;
  height: 30px;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  -webkit-box-pack: justify;
  -ms-flex-pack: justify;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.flexLeft {
  cursor: pointer;
  width: 100%;
  height: 30px;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  -webkit-box-pack: justify;
  -ms-flex-pack: justify;
  font-size: 14px;
  padding-right: 8px;
}
.choosebox ::v-deep .el-checkbox {
}
.el-checkbox {
  display: block !important;
  height: 30px;
  line-height: 30px;
}
ul,
li {
  list-style: none;
  padding-inline-start: 0;
  margin-block-start: 0;
  margin-block-end: 0;
}
li {
  height: 30px;
  line-height: 30px;
  padding: 0 20px;
}
.userlist {
  width: 100%;
  display: flex;
  justify-content: space-between;
}

@media only screen and (max-width: 470px) {
  .message-delete {
    width: 300px;
  }
  .el-message {
    min-width: 300px;
  }
  .el-dialog {
    margin-top: 54vh !important;
  }
}
</style>
