<!-- 用户信息组件 -->
<template>
  <div>
    <div class="sui-slider">
      <div class="sui-slider-main">
        <div class="sui-slider-title">
          <h2>
            <span class="sui-slider-title-text">用户信息</span>
          </h2>
          <span
            @click="close"
            class="sui-icons sui-icons-close sui-slider-title-x"
          ></span>
        </div>
        <div class="sui-slider-content">
          <el-row v-if="operate1 === 'index'">
            <div class="content">
              <div class="img_holder">
                <template v-if="operate === 'detail'">
                  <img
                    v-if="formItem.profilePhoto"
                    :src="
                      'data:image/' +
                      formItem.photo +
                      ';base64,' +
                      formItem.photo
                    "
                    style="margin-top: -15px; width: 55px; height: 55px"
                  />
                  <img
                    v-else
                    src="../../../assets/img/photo-default.png"
                    style="margin-top: -15px; width: 55px; height: 55px"
                  />
                </template>
                <template v-else>
                  <input
                    type="file"
                    ref="avatarInput"
                    accept="image/gif, image/jpeg, image/jpg, image/png"
                    @change="loadImg"
                    placeholder="请输入"
                    size="small"
                    style="display: none"
                  />
                  <img
                    v-if="headerSrc"
                    :src="headerSrc"
                    style="margin-top: -15px; width: 55px; height: 55px"
                    @click="headerInputClick"
                  />
                  <img
                    v-else-if="formItem.profilePhoto"
                    :src="
                      'data:image/' +
                      formItem.photo +
                      ';base64,' +
                      formItem.photo
                    "
                    @click="headerInputClick"
                    style="margin-top: -15px; width: 55px; height: 55px"
                  />
                  <img
                    v-else
                    src="../../../assets/img/photo-default.png"
                    @click="headerInputClick"
                    style="margin-top: -15px; width: 55px; height: 55px"
                  />
                </template>
              </div>
            </div>
          </el-row>
          <el-form
            class="userModal"
            ref="formItem"
            :rules="ruleValidate"
            :model="formItem"
            label-width="80px"
          >
            <el-row>
              <el-col :span="24" style="marginBottom: 20px"
                ><span style="fontSize: 15px">基本信息：</span></el-col
              >
              <el-col :span="8">
                <el-form-item label="账户" prop="userCode">
                  <el-input
                    v-model="formItem.userCode"
                    placeholder="请输入"
                    :disabled="operate === 'detail' || operate === 'edit'"
                    size="small"
                  ></el-input>
                </el-form-item>
                <el-form-item label="用户ID" prop="userId" v-show="false">
                  <el-input
                    v-model="formItem.userId"
                    placeholder="请输入"
                    size="small"
                  ></el-input>
                </el-form-item>
                <el-form-item label="账户" prop="profilePhoto" v-show="false">
                  <el-input
                    v-model="formItem.profilePhoto"
                    placeholder="请输入"
                    size="small"
                  ></el-input>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="8">
              <el-form-item label="所属集团" prop="groupData" v-if="userCode === 'admin'">
                <el-select v-model="formItem.groupData" filterable collapse-tags placeholder="请选择所属集团" size="small" @change='changeGroup' :disabled="(operate1 ==='index' || operate === 'detail')">
                    <el-option
                    v-for="item in tableData"
                    :key="item.id"
                    :label="item.groupName"
                    :value="item.id">
                    </el-option>
                </el-select>
              </el-form-item>
              </el-col>-->
              <el-col
                :span="8"
                style="height: 41px"
                v-if="userCode === 'admin'"
              >
                <el-form-item label="所属租户" prop="companyData">
                  <el-select
                    v-model="formItem.companyData"
                    filterable
                    collapse-tags
                    @change="changeCompany"
                    placeholder="请选择所属租户"
                    size="small"
                    :disabled="operate1 === 'index' || operate === 'detail'"
                  >
                    <el-option
                      v-for="item in companys1"
                      :key="item.id"
                      :label="item.companyName"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <!-- </el-row>
              <el-row>-->
              <el-col :span="8" style="height: 41px">
                <el-form-item label="所属机构" prop="orgCode">
                  <el-select
                    v-model="formItem.orgCode"
                    style="width: 100%"
                    @change="changeOrg"
                    filterable
                    clearable
                    placeholder="请选择机构"
                    size="small"
                    :filter-method="filterSelect"
                    :disabled="operate1 === 'index' || operate === 'detail'"
                  >
                    <el-option
                      ref="orgselect"
                      :key="formItem.id"
                      :value="formItem.orgCode"
                      :label="formItem.orgName"
                      style="height: auto; padding: 0 15px 0 0"
                    >
                      <el-tree
                        :data="orgTree.tree"
                        highlight-current
                        node-key="id"
                        show-checkbox
                        check-strictly
                        check-on-click-node
                        :default-expanded-keys="defaultExpand"
                        ref="orgtree"
                        @node-collapse="nodeUpdate2"
                        @node-expand="nodeUpdate1"
                        :props="defaultProps"
                        :v-loading="orgTreeLoading"
                        :filter-node-method="filterOrgTree"
                        @check-change="handleCheckChange"
                      ></el-tree>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="姓名" prop="userName">
                  <el-input
                    v-model="formItem.userName"
                    @focus="inputC.nameFocus = true"
                    @blur="inputC.nameFocus = false"
                    placeholder="请输入"
                    :disabled="operate === 'detail'"
                    size="small"
                  ></el-input>
                  <span
                    v-if="
                      formItem.userName &&
                      charLength(formItem.userName) <= 50 &&
                      inputC.nameFocus
                    "
                    class="showLen"
                    >剩余{{ 50 - charLength(formItem.userName) }}个字符</span
                  >
                </el-form-item>
              </el-col>
              <el-col :span="8" style="height: 41px">
                <el-form-item label="岗位" prop="dutys">
                  <el-select
                    v-model="formItem.dutys"
                    :disabled="operate1 === 'index' || operate === 'detail'"
                    placeholder="请选择岗位"
                    size="small"
                    clearable
                    multiple
                    collapse-tag
                  >
                    <el-option
                      v-for="item in dutyList"
                      :key="item.dutyId"
                      :label="item.dutyName"
                      :value="item.dutyId"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="邮箱" prop="email">
                  <el-input
                    v-model="formItem.email"
                    :disabled="operate === 'detail'"
                    @focus="inputC.email = true"
                    @blur="inputC.email = false"
                    placeholder="请输入邮箱"
                    size="small"
                  ></el-input>
                  <!-- <span v-if="formItem.email && charLength(formItem.email) <= 100 && inputC.email" class="showLen">
                    剩余{{100 - charLength(formItem.email)}}个字符
                  </span>-->
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="手机" prop="mobile">
                  <el-input
                    v-model.trim="formItem.mobile"
                    :disabled="operate === 'detail'"
                    placeholder="请输入"
                    size="small"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8" style="height: 41px">
                <el-form-item label="角色" prop="qrRole">
                  <el-select
                    v-model="qrRole"
                    filterable
                    multiple
                    collapse-tags
                    placeholder="请选择角色"
                    size="small"
                    :disabled="operate1 === 'index' || operate === 'detail'"
                  >
                    <el-option
                      v-for="item in roleList"
                      :key="item.roleId"
                      :label="item.roleName + '(' + item.appName +')'"
                      :value="item.roleId"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="入职日期" prop="entryDate">
                  <el-date-picker
                    v-model="formItem.entryDate"
                    value-format="yyyy-MM-dd"
                    :disabled="operate1 === 'index' || operate === 'detail'"
                    style="width: 100%"
                    type="date"
                    placeholder="选择日期"
                    size="small"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
              <!-- </el-row>
              <el-row>-->
              <el-col :span="8">
                <el-form-item label="性别" prop="sex">
                  <el-select
                    placeholder="请选择"
                    v-model="formItem.sex"
                    :disabled="operate === 'detail'"
                    size="small"
                    class="user-select"
                  >
                    <el-option value="1" label="男"></el-option>
                    <el-option value="0" label="女"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="身份证号" prop="cardNo">
                  <el-input
                    v-model="formItem.cardNo"
                    :disabled="operate === 'detail'"
                    @focus="inputC.cardNo = true"
                    @blur="inputC.cardNo = false"
                    placeholder="请输入"
                    size="small"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="年龄" prop="age">
                  <!-- <el-input-number
                    :max="100"
                    :min="1"
                    v-model="formItem.age"
                    :disabled="operate === 'detail'"
                    style="width: 100%"
                    size="small"
                  ></el-input-number> -->
                  <el-input
                    readonly="readonly"
                    v-model="formItem.age"
                    :disabled="operate === 'detail'"
                    style="width: 100%"
                    size="small"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8" style="height: 41px">
                <el-form-item label="职级" prop="rank">
                  <el-select
                    v-model="formItem.rank"
                    :disabled="operate1 === 'index' || operate === 'detail'"
                    placeholder="请选择职级"
                    size="small"
                    clearable
                    collapse-tags
                  >
                    <el-option
                      v-for="item in dictList"
                      :key="item.dictCode"
                      :label="item.dictName"
                      :value="item.dictCode"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <!-- </el-row>
              <el-row>-->
              <el-col :span="8">
                <el-form-item label="出生日期" prop="birthDate">
                  <el-date-picker
                    v-model="formItem.birthDate"
                    value-format="yyyy-MM-dd"
                    style="width: 100%"
                    type="date"
                    placeholder="选择日期"
                    size="small"
                    :disabled="true"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="籍贯" prop="nativePlace">
                  <el-input
                    v-model="formItem.nativePlace"
                    :disabled="operate === 'detail'"
                    @focus="inputC.nativePlace = true"
                    @blur="inputC.nativePlace = false"
                    placeholder="请输入"
                    size="small"
                  ></el-input>
                  <span
                    v-if="
                      formItem.nativePlace &&
                      charLength(formItem.nativePlace) <= 50 &&
                      inputC.nativePlace
                    "
                    class="showLen"
                    >剩余{{ 50 - charLength(formItem.nativePlace) }}个字符</span
                  >
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="政治面貌" prop="political">
                  <el-select
                    placeholder="请选择"
                    v-model="formItem.political"
                    :disabled="operate === 'detail'"
                    size="small"
                    class="user-select"
                  >
                    <el-option
                      v-for="item in politicalList"
                      :key="item.value"
                      :label="item.name"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24" style="marginBottom: 20px"
                ><span style="fontSize: 15px">其他信息：</span></el-col
              >
              <!-- </el-row>
              <el-row>-->
              <el-col :span="8">
                <el-form-item label="文化程度" prop="degree">
                  <el-select
                    placeholder="请选择"
                    v-model="formItem.degree"
                    :disabled="operate === 'detail'"
                    size="small"
                    class="user-select"
                  >
                    <el-option
                      v-for="item in degreeList"
                      :key="item.value"
                      :label="item.name"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="毕业院校" prop="gradSchool">
                  <el-input
                    v-model="formItem.gradSchool"
                    :disabled="operate === 'detail'"
                    @focus="inputC.gradSchool = true"
                    @blur="inputC.gradSchool = false"
                    placeholder="请输入"
                    size="small"
                  ></el-input>
                  <span
                    v-if="
                      formItem.gradSchool &&
                      charLength(formItem.gradSchool) <= 100 &&
                      inputC.gradSchool
                    "
                    class="showLen"
                    >剩余{{ 100 - charLength(formItem.gradSchool) }}个字符</span
                  >
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="专业" prop="major">
                  <el-input
                    v-model="formItem.major"
                    :disabled="operate === 'detail'"
                    @focus="inputC.gradSchool = true"
                    @blur="inputC.gradSchool = false"
                    placeholder="请输入"
                    size="small"
                  ></el-input>
                  <span
                    v-if="
                      formItem.major &&
                      charLength(formItem.major) <= 50 &&
                      inputC.gradSchool
                    "
                    class="showLen"
                    >剩余{{ 50 - charLength(formItem.major) }}个字符</span
                  >
                </el-form-item>
              </el-col>
              <!-- </el-row>
              <el-row>-->
              <el-col :span="8">
                <el-form-item label="IP地址" prop="ip">
                  <el-input
                    v-model.trim="formItem.ip"
                    :disabled="operate1 === 'index' || operate === 'detail'"
                    placeholder="请输入"
                    size="small"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="职称" prop="title">
                  <el-input
                    v-model="formItem.title"
                    :disabled="operate === 'detail'"
                    @focus="inputC.title = true"
                    @blur="inputC.title = false"
                    placeholder="请输入"
                    size="small"
                  ></el-input>
                  <span
                    v-if="
                      formItem.title &&
                      charLength(formItem.title) <= 50 &&
                      inputC.title
                    "
                    class="showLen"
                    >剩余{{ 50 - charLength(formItem.title) }}个字符</span
                  >
                </el-form-item>
              </el-col>
              <!-- </el-row>
              <el-row>-->
              <el-col :span="24">
                <el-form-item label="职责" prop="responsibility">
                  <el-input
                    v-model="formItem.responsibility"
                    :disabled="operate === 'detail'"
                    placeholder="请输入"
                    size="small"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="在职状态"
                  prop="leave"
                  v-show="operate === 'detail' || operate === 'edit'"
                >
                  <el-select
                    v-model="formItem.leave"
                    :disabled="operate1 === 'index'"
                    size="small"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in leaveStatus"
                      :key="item.value"
                      :label="item.name"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="密码有效期" prop="expireDays">
                  <el-input
                    class="expireDays"
                    v-model="formItem.expireDays"
                    :disabled="operate1 === 'index' || operate === 'detail'"
                    placeholder="默认无限，单位(天)"
                    size="small"
                  ></el-input>
                  <span style="color: #6f6f6f; display: inline">天</span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="创建日期"
                  prop="crtDate"
                  v-show="operate === 'detail' || operate === 'edit'"
                >
                  <el-input
                    v-model="formItem.crtDate"
                    :disabled="true"
                    size="small"
                  ></el-input>
                </el-form-item>
              </el-col>
              <!-- </el-row>
              <el-row>-->
              <el-col :span="24">
                <el-form-item label="地址" prop="homeAddr">
                  <el-input
                    v-model="formItem.homeAddr"
                    :disabled="operate === 'detail'"
                    @focus="inputC.homeAddr = true"
                    @blur="inputC.homeAddr = false"
                    placeholder="请输入"
                    size="small"
                  ></el-input>
                  <span
                    v-if="
                      formItem.homeAddr &&
                      charLength(formItem.homeAddr) <= 100 &&
                      inputC.homeAddr
                    "
                    class="showLen"
                    >剩余{{ 100 - charLength(formItem.homeAddr) }}个字符</span
                  >
                </el-form-item>
              </el-col>
              <!-- </el-row>
              <el-row>-->
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input
                    v-model="formItem.remark"
                    :disabled="operate === 'detail'"
                    @focus="inputC.remark = true"
                    @blur="inputC.remark = false"
                    placeholder="请输入"
                    type="textarea"
                    :autosize="{ minRows: 2, maxRows: 5 }"
                    size="small"
                  ></el-input>
                </el-form-item>
                <span
                  v-if="
                    formItem.remark &&
                    charLength(formItem.remark) <= 512 &&
                    inputC.remark
                  "
                  class="showLen"
                  style="margin-left: 80px"
                  >剩余{{ 512 - charLength(formItem.remark) }}个字符</span
                >
              </el-col>
            </el-row>
            <el-form-item v-if="operate !== 'detail'">
              <el-button
                type="primary"
                :loading="buttonLoading"
                style="float: right"
                @click="formSubmit"
                size="small"
                >保 存1</el-button
              >
              <el-button
                plain
                v-if="formItem.orgCode != '' && orgRelateButtonControll"
                style="float: right; margin-right: 20px"
                @click="dialogFormVisible = true"
                size="small"
                >用户机构职级关联管理</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="sui-slider-cover" @click="close"></div>
    </div>
    <el-dialog
      title="用户机构职级关联管理"
      :visible.sync="dialogFormVisible"
      :before-close="handleClose"
    >
      <el-form
        label-position="right"
        label-width="65px"
        :model="orgForm"
        ref="orgForm"
        show-message
        style="margin: 15px 30px; width: calc(100% - 60px)"
      >
        <el-form-item>
          <el-button
            size="small"
            plain
            style="
              color: rgb(64, 158, 255);
              margin-bottom: 10px;
              margin-left: 5px;
            "
            @click="addOrgLink"
            v-if="
              operate === 'add' || (operate === 'edit' && operate1 !== 'index')
            "
            >新增机构岗位关联</el-button
          >
        </el-form-item>
        <el-form-item
          v-for="(params, index) in orgForm.OrgLinks"
          :key="index"
          label="所在机构"
          :required="true"
        >
          <el-row :gutter="10">
            <el-col :span="11" style="margin-bottom: 10px">
              <el-form-item
                label-width="0"
                prop="orgCode"
                :rules="{
                  required: true,
                  message: '所在机构不能为空',
                  trigger: 'blur',
                }"
              >
                <el-select
                  v-model="params.orgId"
                  style="width: 100%"
                  @change="changeOrg"
                  filterable
                  clearable
                  placeholder="请选择机构"
                  size="small"
                  :filter-method="
                    (val) => {
                      filterSelect1(val, index);
                    }
                  "
                  :disabled="operate === 'edit' && operate1 === 'index'"
                >
                  <el-option
                    ref="orgselect1"
                    :key="params.id"
                    :value="params.orgId"
                    :label="params.orgName"
                    style="height: auto; padding: 0 15px 0 0"
                  >
                    <el-tree
                      :data="orgTree.tree"
                      highlight-current
                      node-key="id"
                      show-checkbox
                      check-strictly
                      check-on-click-node
                      :default-expanded-keys="[params.pId || '']"
                      :ref="'orgtree' + index"
                      :props="defaultProps"
                      :v-loading="orgTreeLoading1"
                      :default-checked-keys="[params.orgId || '']"
                      :filter-node-method="filterOrgTree"
                      @check-change="
                        (data, checked, node) => {
                          handleCheckChange1(
                            data,
                            checked,
                            node,
                            index,
                            params.orgCode
                          );
                        }
                      "
                    ></el-tree>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="10" style="margin-bottom: 10px">
              <el-form-item label="岗位" prop="dutys">
                <el-select
                  v-model="params.dutyId"
                  placeholder="请选择岗位"
                  @change="changeDuty(params)"
                  size="small"
                  clearable
                  :disabled="operate === 'edit' && operate1 === 'index'"
                >
                  <el-option
                    v-for="item in dutyList"
                    :key="item.dutyId"
                    :label="item.dutyName"
                    :value="item.dutyId"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-button
                size="mini"
                type="danger"
                plain
                @click="removeOrgLink(params, index)"
                style="padding: 6px 11px; margin-left: 5px"
                v-if="operate1 !== 'index' && index !== 0"
                >删除</el-button
              >
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="orgLinkCancel" size="small">确定</el-button>
        <!-- <el-button type="primary" @click="orgLinkConfirm" size="small" v-if="operate1 !=='index'">确 定
        </el-button>-->
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  checkCharLength2,
  checkCardNo,
  checkChar,
  checkIpAddress,
  checkTel,
  checkCharNoChinese,
  checkEmail,
  checkInteger,
} from "@/utils/validator.js";
import { objAssign, dgTree, getCookie } from "@/utils/util.js";
import store from "@/store/index.js";
import moment from "moment";
import dataDictionary from "@/store/dataDictionary.js";
export default {
  props: {
    //  操作类型
    operate: {
      type: String,
      // 查看
      default: "detail",
    },
    operate1: {
      type: String,
      default: "1",
    },
    //  数据
    item: Object,
    // 公司id
    passcompanyId: {
      type: String,
      default: "",
    },
    appCode: {
      type: String,
      default: "",
    },
    dataDictionary,
  },
  data() {
    var validateNumberPass = (rule, value, callback) => {
      if (value <= 1) {
        callback("99999");
      } else {
        callback();
      }
    };
    return {
      store,
      buttonLoading: false,
      userCompany: {},
      userGroup: {},
      userCode: "",
      groupId: "",
      headerSrc: "",
      tableData: [],
      companys1: [],
      formItem: {
        userId: "",
        userCode: "",
        userName: "",
        qrCode: "",
        sex: "",
        age: null,
        cardNo: "",
        birthDate: "",
        nativePlace: "",
        orgCode: "",
        orgName: "",
        dep: "",
        workTeam: "",
        profilePhoto: "",
        photo: "",
        mobile: "",
        qq: "",
        wechat: "",
        tel: "",
        email: "",
        homeAddr: "",
        entryDate: "",
        workDate: "",
        political: "",
        dutys: "",
        title: "",
        degree: "",
        major: "",
        gradSchool: "",
        ability: "",
        tranHis: "",
        certificate: "",
        special: "",
        assessment: "",
        leaveStatus: "",
        onlineStatus: "",
        status: "",
        remark: "",
        expireDays: null,
        leave: "",
        address: "",
        ip: "",
        rank: "",
        responsibility: "",
        groupData: "",
        companyData: "",
        groupId: "",
        companyId: "",
      },
      dictList: [],
      dutyList: [],
      orgTree: {
        tree: [],
        items: [],
      },
      orgTreeLoading: true,
      orgTreeLoading1: true,
      defaultExpand: [], // 默认展开已选
      defaultExpand1: [], // 默认展开已选
      ruleValidate: {
        userCode: [
          {
            required: true,
            message: "用户编码不能为空",
            trigger: "change",
          },
          {
            validator: checkCharLength2,
            max: 36,
            trigger: "change",
          },
          {
            validator: checkCharNoChinese,
            trigger: "change",
          },
        ],
        userName: [
          {
            required: true,
            message: "用户姓名不能为空",
            trigger: "change",
          },
          {
            validator: checkCharLength2,
            max: 50,
            trigger: "change",
          },
        ],
        orgCode: [
          {
            required: true,
            message: "所属机构不能为空",
            trigger: "change",
          },
          {
            validator: checkCharLength2,
            max: 255,
            trigger: "change",
          },
        ],
        groupData: [
          {
            required: true,
            message: "所属集团不能为空",
            trigger: "change",
          },
          {
            validator: checkCharLength2,
            max: 255,
            trigger: "change",
          },
        ],
        companyData: [
          {
            required: true,
            message: "所属租户不能为空",
            trigger: "change",
          },
          {
            validator: checkCharLength2,
            max: 255,
            trigger: "change",
          },
        ],
        mobile: [
          {
            required: true,
            validator: checkTel,
            trigger: "change",
          },
        ],
        // entryDate: [
        //   {required: true, message: '入职时间不能为空', trigger: 'change'}
        // ],
        dutys: [
          { required: true, message: "岗位不能为空", trigger: "change" },
          // {validator: checkCharLength2,  max: 50, trigger: 'change'},
          // { validator: checkChar, trigger: 'change' }
        ],
        qrCode: [
          {
            validator: checkCharLength2,
            max: 255,
            trigger: "change",
          },
        ],
        cardNo: [
          {
            validator: checkCardNo,
            trigger: "change",
          },
        ],
        nativePlace: [
          {
            validator: checkCharLength2,
            max: 50,
            trigger: "change",
          },
          {
            validator: checkChar,
            trigger: "change",
          },
        ],
        dep: [
          {
            validator: checkCharLength2,
            max: 100,
            trigger: "change",
          },
        ],
        workTeam: [
          {
            validator: checkCharLength2,
            max: 10,
            trigger: "change",
          },
        ],
        profilePhoto: [
          {
            validator: checkCharLength2,
            max: 255,
            trigger: "change",
          },
        ],
        qq: [
          {
            validator: checkCharLength2,
            max: 36,
            trigger: "change",
          },
        ],
        wechat: [
          {
            validator: checkCharLength2,
            max: 36,
            trigger: "change",
          },
        ],
        tel: [
          {
            validator: checkCharLength2,
            max: 36,
            trigger: "change",
          },
        ],
        email: [
          {
            required: true,
            validator: checkCharLength2,
            max: 100,
            trigger: "change",
          },
          {
            required: true,
            validator: checkEmail,
            trigger: "change",
          },
        ],
        homeAddr: [
          {
            validator: checkCharLength2,
            max: 100,
            trigger: "change",
          },
          {
            validator: checkChar,
            trigger: "change",
          },
        ],
        political: [
          {
            validator: checkCharLength2,
            max: 10,
            trigger: "change",
          },
          {
            validator: checkChar,
            trigger: "change",
          },
        ],
        title: [
          {
            validator: checkCharLength2,
            max: 50,
            trigger: "change",
          },
          {
            validator: checkChar,
            trigger: "change",
          },
        ],
        degree: [
          {
            validator: checkCharLength2,
            max: 50,
            trigger: "change",
          },
          {
            validator: checkChar,
            trigger: "change",
          },
        ],
        major: [
          {
            validator: checkCharLength2,
            max: 50,
            trigger: "change",
          },
          {
            validator: checkChar,
            trigger: "change",
          },
        ],
        gradSchool: [
          {
            validator: checkCharLength2,
            max: 100,
            trigger: "change",
          },
          {
            validator: checkChar,
            trigger: "change",
          },
        ],
        ability: [
          {
            validator: checkCharLength2,
            max: 100,
            trigger: "change",
          },
        ],
        tranHis: [
          {
            validator: checkCharLength2,
            max: 512,
            trigger: "change",
          },
        ],
        certificate: [
          {
            validator: checkCharLength2,
            max: 512,
            trigger: "change",
          },
        ],
        special: [
          {
            validator: checkCharLength2,
            max: 100,
            trigger: "change",
          },
        ],
        assessment: [
          {
            validator: checkCharLength2,
            max: 512,
            trigger: "change",
          },
        ],
        workDate: [
          {
            validator: checkCharLength2,
            max: 200,
            trigger: "change",
          },
        ],
        remark: [
          {
            validator: checkCharLength2,
            max: 512,
            trigger: "change",
          },
          {
            validator: checkChar,
            trigger: "change",
          },
        ],
        expireDays: [
          {
            validator: checkInteger,
            trigger: "change",
          },
          {
            validator: checkCharLength2,
            max: 4,
            trigger: "change",
          },
          // {validator: validateNumberPass, trigger: 'change'}
        ],
        ip: [
          {
            validator: checkCharLength2,
            max: 20,
            trigger: "change",
          },
          {
            validator: checkIpAddress,
            trigger: "change",
          },
        ],
      },
      roleList: [],
      qrRole: [],
      userRoles: [], // 用户与角色关联信息
      leaveStatus: [
        {
          name: "在职",
          value: "0",
        },
        {
          name: "离退",
          value: "1",
        },
        {
          name: "离休",
          value: "2",
        },
      ],
      politicalList: [
        {
          name: "中共党员",
          value: "0",
        },
        {
          name: "中共预备党员",
          value: "1",
        },
        {
          name: "共青团员",
          value: "2",
        },
        {
          name: "民革党员",
          value: "3",
        },
        {
          name: "民盟盟员",
          value: "4",
        },
        {
          name: "民建会员",
          value: "5",
        },
        {
          name: "民进会员",
          value: "6",
        },
        {
          name: "农工党党员",
          value: "7",
        },
        {
          name: "致公党党员",
          value: "8",
        },
        {
          name: "九三学社社员",
          value: "9",
        },
        {
          name: "台盟盟员",
          value: "10",
        },
        {
          name: "无党派人士",
          value: "11",
        },
        {
          name: "群众",
          value: "12",
        },
      ],
      degreeList: [
        {
          name: "博士",
          value: "0",
        },
        {
          name: "硕士",
          value: "1",
        },
        {
          name: "本科",
          value: "2",
        },
        {
          name: "大专",
          value: "3",
        },
        {
          name: "中专",
          value: "4",
        },
        {
          name: "技工学校",
          value: "5",
        },
        {
          name: "高中",
          value: "6",
        },
        {
          name: "初中",
          value: "7",
        },
        {
          name: "小学",
          value: "8",
        },
        {
          name: "半文盲",
          value: "9",
        },
        {
          name: "文盲",
          value: "10",
        },
      ],
      inputC: {
        nameFocus: false,
        nativePlace: false,
        email: false,
        political: false,
      },
      oldDutyList: [],
      dialogFormVisible: false,
      orgForm: {
        OrgLinks: [],
      },
      isSaveUserInfo: false, //在机构关联 是否点击保存了
      orgRelateButtonControll: false,
      searchForm: {
        companyId: ''
      },
      EntryListData: []
    };
  },

  created() {
    //  加入
    this.item.entryDate = this.item.entryDate
      ? moment(new Date(this.item.entryDate)).format("YYYY-MM-DD")
      : "";
    this.formItem = objAssign(this.formItem, this.item);
    if (this.formItem.rank !== null && this.formItem.rank !== "") {
      this.formItem.rank = this.formItem.rank.split(",");
    }
    if (this.formItem.dutys !== null && this.formItem.dutys.length > 0) {
      let list = [];
      for (let duty of this.formItem.dutys) {
        list.push(duty.dutyId);
      }
      this.formItem.dutys = list;
    }
    // this.formItem.groupData = this.formItem.groupId === null || this.formItem.groupId === '' ? '' : this.formItem.groupId
    // this.formItem.companyData = this.formItem.companyId === null || this.formItem.companyId === '' ? [] : this.formItem.companyId.split(',')
    this.formItem.photoType = this.formItem.profilePhoto
      ? this.formItem.profilePhoto.substr(
          this.formItem.profilePhoto.indexOf(".") + 1
        )
      : "";
    if (
      this.item.hasOwnProperty("sysUserLogin") &&
      this.item.sysUserLogin !== null
    ) {
      this.formItem.leave = this.item.sysUserLogin.leave;
    }
    if (this.operate !== "add") {
      this.formItem.crtDate = this.item.crtDate
        ? this.item.crtDate.substr(0, 10)
        : "";
      let num =
        this.item.sysUserLogin && this.item.sysUserLogin.expireDays
          ? this.item.sysUserLogin.expireDays
          : "";
      this.formItem.expireDays =
        this.item.sysUserLogin &&
        this.item.sysUserLogin.expireDays &&
        Number(this.item.sysUserLogin.expireDays) < 0
          ? "密码已过期"
          : num;
    }
    if (this.formItem.userId) {
      this.getUserRole(this.formItem.userId);
    }
  },
  watch: {
    "formItem.dutys": function (n, o) {
      let that = this;
      if (n.length === 2) {
        that.formItem.dutys = n.filter((x) => !o.includes(x));
      }
      let dutys = that.formItem.dutys[0];
      let arr = that.orgForm.OrgLinks;
      if (arr.length === 0) {
        this.orgForm.OrgLinks.push({
          orgId: that.formItem.orgId === undefined ? "" : that.formItem.orgId,
          dutyId: this.formItem.dutys[0],
          orgName: this.formItem.orgName,
          orgCode: this.formItem.orgCode,
        });
      } else {
        for (let index = 0; index < arr.length; index++) {
          const element = arr[index];
          if (this.formItem.orgCode === element.orgCode) {
            element.dutyId = that.formItem.dutys[0];
            that.formItem.orgId =
              that.formItem.orgId === undefined ? "" : that.formItem.orgId;
          }
        }
      }
    },
    dialogFormVisible: function (n) {
      if (n) {
        if (
          this.formItem.orgId === undefined &&
          this.formItem.orgCode === undefined
        ) {
          // 获取职级-机构关联信息
          this.getOrgDutyInfo(this.passcompanyId);
        } else {
          let dutys = this.formItem.dutys[0],
            orgId = this.formItem.orgId;
          let arr = this.orgForm.OrgLinks;
          if (arr.length === 0) {
            this.orgForm.OrgLinks.push({
              orgId: this.formItem.orgId,
              dutyId: this.formItem.dutys[0],
              orgName: this.formItem.orgName,
              orgCode: this.formItem.orgCode,
              label: true,
            });
          }
        }
        if (this.orgForm.OrgLinks.length !== 0) {
          this.orgForm.OrgLinks.map((_item, index) => {
            /**
             * @description 弹窗 关联 为用户信息 和 弹窗设置联动 tree 以及tree展开联动
             */
            dgTree(this.orgTree.tree, "children", (item) => {
              if (item.orgCode === _item.orgCode) {
                this.$set(this.orgForm.OrgLinks[index], "orgId", item.orgId);
                this.$set(
                  this.orgForm.OrgLinks[index],
                  "orgName",
                  item.orgName
                );
                this.$nextTick(() => {
                  this.$refs["orgtree" + index][0].setCheckedNodes([item]);
                });
                if (item.pId !== null && item.pId !== "") {
                  this.$set(this.orgForm.OrgLinks[index], "pId", item.pId);
                } else {
                  this.$set(this.orgForm.OrgLinks[index], "pId", "");
                }
              }
            });
            /**联动结束*/
          });
        }
      }
    },
    "formItem.orgCode": {
      immediate: true,
      handler: function (n, o) {
        // if (o !== null && o === "") {
        //   this.qrRole = [];
        // }
        if (n === "" || n === null) {
          this.$nextTick(() => {
            this.$refs.orgtree.setCheckedNodes([]);
          });
        }
        let dutys = this.formItem.dutys[0],
          orgId = this.formItem.orgId;
        let arr = this.orgForm.OrgLinks;
        if (arr.length == 0) {
          this.orgForm.OrgLinks.push({
            orgId: this.formItem.orgId,
            dutyId: this.formItem.dutys[0],
            orgName: this.formItem.orgName,
            orgCode: this.formItem.orgCode,
            label: true,
          });
        } else {
          /**只控制绑定的 职级关联 的第一条（目前第一条） */
          for (let index = 0; index < arr.length; index++) {
            const element = arr[index];
            if (
              (o === element.orgCode &&
                element.label &&
                this.formItem !== "") ||
              this.operate === "add"
            ) {
              this.$set(
                this.orgForm.OrgLinks[index],
                "orgId",
                this.formItem.orgId
              );
              this.$set(
                this.orgForm.OrgLinks[index],
                "dutyId",
                Array.isArray(this.formItem.dutys)
                  ? this.formItem.dutys[0]
                  : this.formItem.dutys
              );
              this.$set(
                this.orgForm.OrgLinks[index],
                "orgName",
                this.formItem.orgName
              );
              this.$set(
                this.orgForm.OrgLinks[index],
                "orgCode",
                this.formItem.orgCode
              );
              this.$set(this.orgForm.OrgLinks[index], "label", true);
            }
          }
        }
      },
    },
    "formItem.birthDate"(n, o) {
      let date = new Date();
      let dateBrith = new Date(n);
      let yearNow = date.getFullYear();
      let yearBirth = dateBrith.getFullYear();
      if (n) {
        this.formItem.age = parseInt(yearNow) - parseInt(yearBirth);
      }
    },
    "formItem.cardNo"(n, o) {
      let _reg = /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/;
      if (_reg.test(n)) {
        this.IDCardChange(n);
      }
    },
  },
  computed: {
    //  树配置
    defaultProps() {
      return this.store.state.system.organizManage.defaultProps;
    },
    //  展开数组
    expandedKeys: {
      get: function () {
        return this.store.state.system.organizManage.expandedKeys;
      },
      set: function (data) {
        this.store.commit("system/organizManage/expandedKeys", data);
      },
    },
    //  选中节点数据
    treeItem() {
      return this.store.state.system.sysPosts.treeItem;
    },
  },
  mounted() {
    this.initData();
    this.userCompany = JSON.parse(window.top.localStorage.getItem("companys"));
    this.userGroup = JSON.parse(window.top.localStorage.getItem("sysGroup"));
    this.userCode = JSON.parse(getCookie("userInfo")).userCode;
    this.groupId = JSON.parse(getCookie("userInfo")).groupId;
    this.searchGroup();
    this.formItem.groupData =
      this.formItem.groupId === null || this.formItem.groupId === ""
        ? ""
        : this.formItem.groupId;
    this.formItem.companyData =
      this.formItem.companyId === null || this.formItem.companyId === ""
        ? ""
        : this.formItem.companyId;
    // 当以添加页面进来
    this.searchCompany("");
    if (this.operate === "add") {
      // 当前登录用户非视拓超级管理员，且公司只有一个时，直接请求机构数据，和角色数据
      if (this.userCode !== "admin") {
        // 请求机构
        this.getorganTree(this.passcompanyId);
        //  请求角色
        this.getRoles(this.passcompanyId);
        // 职级
        this.getDistList(this.passcompanyId);
        // 岗位
        this.getDutyList(this.passcompanyId);
        // 获取职级-机构关联信息
        this.getOrgDutyInfo(this.passcompanyId);
      }
      this.orgRelateButtonControll = true;
    } else if (this.operate === "edit") {
      // this.searchCompany(this.formItem.groupId)
      Promise.all([
        this.getorganTree(this.formItem.companyId),
        //  请求角色
        this.getRoles(this.formItem.companyId),
        // 职级
        this.getDistList(this.formItem.companyId),
        // 岗位
        this.getDutyList(this.formItem.companyId),
        // 获取用户已有岗位信息
        this.getUserOldDuty(this.formItem.companyId),
        // 获取职级-机构关联信息
      ]).then((res) => {
        this.getOrgDutyInfo(this.formItem.companyId).then((res) => {
          this.orgRelateButtonControll = true;
        });
      });
    }
    // 判断所属机构的正则有效
    if (this.operate1 === "index" || this.operate === "detail") {
      this.ruleValidate.orgCode = [];
    } else {
      this.ruleValidate.orgCode = [
        {
          required: true,
          message: "所属机构不能为空",
          trigger: "change",
        },
        {
          validator: checkCharLength2,
          max: 255,
          trigger: "change",
        },
      ];
    }
  },
  methods: {
    // 改变集团分组，实时更新关联公司信息
    changeGroup(val) {
      let _this = this;
      // 每次改变就清空关联下拉框
      _this.formItem.companyData = "";
      _this.qrRole = [];
      _this.formItem.orgCode = "";
      _this.formItem.orgName = "";
      _this.companys1 = [];
      _this.roleList = [];
      _this.orgTree.tree = [];
      // _this.searchCompany(val)
    },
    changeCompany(val) {
      let _this = this;
      // 每次改变就清空关联下拉框
      _this.qrRole = [];
      _this.formItem.orgCode = "";
      _this.formItem.orgName = "";
      _this.roleList = [];
      _this.orgTree.tree = [];
      // 角色选择
      _this.getRoles(val);
      // 机构选择
      _this.getorganTree(val);
      // 职级
      _this.getDistList(val);
      // 岗位
      _this.getDutyList(val);
      // 更变对应的集团（集团不显示，但仍需更变）
      for (let i = 0; i < _this.companys1.length; i++) {
        if (_this.companys1[i].id === val) {
          _this.formItem.groupData = _this.companys1[i].groupId;
        }
      }
    },
    searchGroup() {
      let _this = this;
      this.axios
        .get("pass/v1/sysgroups/like/", {})
        .then((res) => {
          if (res) {
            _this.tableData = res.data.list;
          }
        })
        .catch(function () {});
    },
    searchCompany(val) {
      let _this = this;
      this.axios
        .get("pass/v1/syscompanys/like/?pageSize=10000&groupId=" + val, {})
        .then((res) => {
          if (res.code === "0") {
            _this.companys1 = res.data.list;
          } else {
            _this.$message.error(res.message);
          }
        })
        .catch(() => {});
    },
    // init
    initData() {
      // 获取角色
      // this.getRoles();
      // this.getDistList();
    },
    // 获取机构树
    getorganTree(value) {
      return this.getOrg(value).then(() => {
        //
        if (!this.item.orgCode) return false;
        //  取当前orgCode的id
        let orgCodeId = "";
        dgTree(this.orgTree.tree, "children", (item) => {
          if (item.orgCode === this.item.orgCode) {
            orgCodeId = item.id;
          }
        });
        let items = [];
        this.dgPid(this.orgTree.tree, orgCodeId, (item) => {
          items.push(item);
        });
        //
        let orgCodeArr = [];
        for (let item of items.reverse()) {
          orgCodeArr.push(item.orgCode);
        }
        //
        this.orgTree.items = orgCodeArr;
      });
    },
    // 获取职级
    getDistList(val) {
      this.axios.get("pass/v1/sysdicts/?pDictId=position_level&companyId=" + val).then((res) => {
        if (res.code === "0") {
          this.dictList = res.data.list;
        } else {
          this.$message.error(res.message);
        }
      });
    },
    // 获取岗位
    getDutyList(val) {
      let form = {
        pageNum: 1,
        pageSize: 100000,
        companyId: val,
      };
      return this.axios
        .get("pass/v1/sysdutys/", {
          params: form,
        })
        .then((res) => {
          if (res.code === "0") {
            this.dutyList = res.data.list;
          } else {
            this.$message.error(res.message);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getUserOldDuty(val) {
      let form = {
        pageNum: 1,
        pageSize: 100000,
        companyId: val,
        resourceId: this.formItem.userId,
        resourceType: "1",
      };
      return this.axios
        .get("pass/v1/sysuserdutys/", {
          params: form,
        })
        .then((res) => {
          if (res.code === "0") {
            this.oldDutyList = res.data.list;
          } else {
            this.$message.error(res.message);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 树形控件过滤数据
    filterOrgTree(value, data) {
      if (!value) return true;
      return data.orgName.indexOf(value) !== -1;
    },
    // 选择机构下拉值筛选
    filterSelect(val) {
      this.$refs.orgtree.filter(val);
    },
    // 选择机构下拉值筛选
    filterSelect1(val, index) {
      let refName = "orgtree" + index;
      this.$refs[refName][0].filter(val);
    },
    //  添加用户
    addUser(form) {
      let data = new FormData();
      for (let key in form) {
        // 岗位单独保存
        if (key !== "dutys") {
          data.append(key, form[key] ? form[key] : "");
        }
      }
      this.store.dispatch("system/usersManage/addUser", data).then((res) => {
        if (res.code === "0") {
          if (this.qrRole.length > 0) {
            this.addRoleToUser(res.data.userId, res.data.userCode);
          }
          if (form.dutys.length > 0) {
            this.addUserDutys(res.data.userId, form.dutys);
          }
          this.$message.success("添加成功");
          this.$emit("on-then", "success", form);
        } else {
          this.$message.error(res.message);
        }
      });
    },
    addUserDutys(userId, list) {
      for (let item of list) {
        let form = {
          dutyId: item,
          resourceId: userId,
          resourceType: "1",
        };
        this.axios
          .post("pass/v1/sysuserdutys/", form)
          .then((res) => {
            if (res.code === "0") {
              this.formItem.userId = userId;
              this.orgLinkConfirm(true);
            } else {
              this.$message.error("岗位添加失败");
            }
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
    // 删除
    deleteOldDuty() {
      for (let item of this.oldDutyList) {
        this.axios
          .delete("pass/v1/sysuserdutys/" + item.id)
          .then((res) => {
            if (res.code === "0") {
              // do
            } else {
              this.$message.error(res.message);
            }
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
    trim: function (s) {
      if (s instanceof String || (typeof s).toLowerCase() == "string") {
        return s.replace(/^\s\s*/, "").replace(/\s\s*$/, "");
      } else {
        return s;
      }
    },
    //  编辑用户
    editUser(form) {
      let data = new FormData();
      let that = this;
      if (this.operate1 === "index") {
        data.append("file", this.$refs.avatarInput.files[0]);
      }
      for (let key in form) {
        if (key !== "qrRole" && key !== "dutys") {
          data.append(key, form[key] ? this.trim(form[key]) : "");
        }
      }
      // 将原有岗位信息删除后重建;
      if (this.oldDutyList.length > 0) {
        this.deleteOldDuty();
      }
      if (form.dutys.length > 0) {
        this.addUserDutys(form.userId, form.dutys);
      }
      this.store
        .dispatch("system/usersManage/editUser", {
          id: form.userId,
          form: data,
        })
        .then((res) => {
          if (res.code === "0") {
            this.$message.success("修改成功");
            that.$emit("editFinish", res.data);
            this.addRoleToUser(res.data.userId, res.data.userCode);
            this.$emit("on-then", "success", {});
          } else {
            this.$message.error(res.message);
          }
        });
    },
    changeOrg() {
      this.$forceUpdate();
    },
    // 选择机构
    handleCheckChange(data, checked, node) {
      let res = this.$refs.orgtree.getCheckedNodes(false, true); //true，1. 是否只是叶子节点 2.选择的时候不包含父节点
      if (res.length > 1) {
        // this.$message.warning('所属机构不可选择多个！');
        this.$refs.orgtree.setCheckedNodes([data]);
      } else if (res.length === 1) {
        /**用户信息中提示勾选tree存在重复 在职级关联已经勾选的中间 */
        if (!this.dialogFormVisible && this.orgRelateButtonControll) {
          let count = 0;
          this.orgForm.OrgLinks.map((item, index) => {
            if (item.orgCode === res[0].orgCode) {
              count++;
            }
          });
          if (count > 0) {
            this.$message.error(
              "当前所勾选的机构, 在职级关联管理的机构中已存在, 请选择其他机构"
            );
            return false;
          }
        }
        this.formItem.orgCode = res[0].orgCode;
        this.formItem.orgName = res[0].orgName;
        this.formItem.orgId = res[0].orgId;
      } else if (res.length === 0) {
        this.formItem.orgCode = "";
        this.formItem.orgName = "";
      }
    },
    // 机构职级弹窗 选择机构
    handleCheckChange1(data, checked, node, index, valOrgCode) {
      let refName = "orgtree" + index;
      let res = this.$refs[refName][0].getCheckedNodes(false, true); //true，1. 是否只是叶子节点 2.选择的时候不包含父节点
      let orgId = "",
        orgName = "",
        orgCode = "";
      if (res.length > 1) {
        orgId = data.orgId;
        orgName = data.orgName;
        orgCode = data.orgCode;
        this.$refs[refName][0].setCheckedNodes([data]);
      } else if (res.length === 1) {
        orgId = res[0].orgId;
        orgName = res[0].orgName;
        orgCode = res[0].orgCode;
        if (valOrgCode === this.formItem.orgCode && index == 0) {
          this.formItem.orgCode = res[0].orgCode;
          this.formItem.orgName = res[0].orgName;
          this.formItem.orgId = res[0].orgId;
          //修改关联树 点击想要的机构之后 同步到侧边栏的表单里面的tree
          //此处代码 后期可以抽离成公共方法
          //直接设置对应的tree setCheckedNodes 并且 修改pId
          let list = [];
          dgTree(this.orgTree.tree, "children", (item) => {
            if (item.orgCode === this.formItem.orgCode) {
              list.push(item);
            }
          });
          this.$refs.orgtree.setCheckedNodes(list);
          if (list[0].pId !== null && list[0].pId !== "") {
            this.defaultExpand.push(list[0].pId);
          }
          //修改结束
        } else {
        }
      } else if (res.length === 0) {
        orgId = "";
        orgName = "";
        orgCode = "";
      }
      this.orgForm.OrgLinks[index].orgId = orgId;
      this.orgForm.OrgLinks[index].orgName = orgName;
      if (index !== 0) {
        this.$set(this.orgForm.OrgLinks[index], "orgCode", orgCode);
      }
      if (res.length !== 0) {
        let array = this.orgForm.OrgLinks,
          count = 0;
        for (let index = 0; index < array.length; index++) {
          const element = array[index];
          if (element.orgId === res[0].orgId) {
            count++;
          }
        }
        if (count > 1) {
          this.$message.error("当前所在机构已经勾选, 请选择其他机构");
          return false;
        }
      }
    },
    // 节点展开更新下拉板
    nodeUpdate1(data) {
      setTimeout(() => {
        let width = this.$refs.orgselect.$el.getElementsByClassName(
          "el-tree"
        )[0].clientWidth;
        let num = document.body.clientWidth - width - 15;
        let allWid =
          parseInt($(".el-select-dropdown")[10].style.left) + width + 15;
        if (allWid > document.body.clientWidth) {
          this.$nextTick(() => {
            $(".el-select-dropdown")[10].style.left = num + "px";
          });
        }
      }, 100);
    },
    // 节点收缩更新下拉板
    nodeUpdate2(data) {
      setTimeout(() => {
        let width = this.$refs.orgselect.$el.getElementsByClassName(
          "el-tree"
        )[0].clientWidth;
        let num = document.body.clientWidth - width - 25;
        let allWid =
          parseInt($(".el-select-dropdown")[10].style.left) + width + 15;
        if (document.body.clientWidth - allWid > 15) {
          this.$nextTick(() => {
            $(".el-select-dropdown")[10].style.left = num + "px";
          });
        }
      }, 500);
    },
    // 编辑用户角色关联信息
    addRoleToUser(userId, userCode) {
      let that = this;
      if (that.qrRole && that.qrRole.length > 0) {
        let oldRole = []; // 已有角色信息
        let hasChange = true;
        for (let i = 0; i < that.userRoles.length; i++) {
          oldRole.push(that.userRoles[i].roleId);
        }
        if (oldRole.length === that.qrRole.length) {
          for (let roleId of oldRole) {
            if (that.qrRole.indexOf(roleId) === -1) {
              hasChange = false;
            }
          }
        }
        if (oldRole.length === that.qrRole.length && hasChange === true) {
          // 原角色信息未被修改，不做操作
        } else {
          let rolesId = "";
          for (let i = 0; i < that.qrRole.length; i++) {
            if (i === 0) {
              rolesId = rolesId + that.qrRole[i];
            } else {
              rolesId = rolesId + "," + that.qrRole[i];
            }
          }
          that.axios
            .post(
              "pass/v1/sysuserroles/batchInsert/" +
                userId +
                "/" +
                userCode +
                "/" +
                rolesId
            )
            .then((res) => {
              // do somthing
            })
            .catch((err) => {
              console.log(err);
            });
        }
      } else {
        if (that.userRoles.length > 0) {
          for (let item of that.userRoles) {
            that.axios
              .delete("pass/v1/sysuserroles/" + item.id)
              .then((res) => {
                // do somthing
              })
              .catch((err) => {
                console.log(err);
              });
          }
        }
      }
    },
    // 获取当前用户角色关联
    getUserRole(userId) {
      let that = this;
      that.axios
        .get(
          "pass/v1/sysuserroles/?userId=" + userId + "&pageNum=1&pageSize=100"
        )
        .then((res) => {
          if (res) {
            for (let i = 0; i < res.data.list.length; i++) {
              that.qrRole.push(res.data.list[i].roleId);
            }
            that.userRoles = res.data.list; // 获取用户角色关联信息
          }
        });
    },
    //  取机构树
    async getOrg(val) {
      //  查询机构树
      const promise = await this.store
        .dispatch("system/organizManage/tree", val)
        .then((res) => {
          if (res.code === "0") {
            //
            dgTree(res.data, "children", (item) => {
              if ("children" in item && item.children.length < 1) {
                delete item.children;
              }
            });
            this.orgTree.tree = res.data;
            if (
              this.formItem.orgCode !== null &&
              this.formItem.orgCode !== ""
            ) {
              this.$nextTick(() => {
                let list = [];
                dgTree(this.orgTree.tree, "children", (item) => {
                  if (item.orgCode === this.formItem.orgCode) {
                    list.push(item);
                    this.formItem.orgName = item.orgName;
                  }
                });
                this.$refs.orgtree.setCheckedNodes(list);
                if (list[0].pId !== null && list[0].pId !== "") {
                  this.defaultExpand.push(list[0].pId);
                }
              });
            }
            this.orgTreeLoading = false;
            this.orgTreeLoading1 = false;
          } else {
            this.$message.error(res.message);
          }
        });
      return promise;
    },
    //  机构树选择
    cascaderChange(items) {
      // console.log(items);
    },
    //  上传头像完成
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    //  save

    //  关闭
    close() {
      this.$refs["formItem"].resetFields();
      this.$emit("on-then", "close", {});
    },
    //  提交
    formSubmit() {
      this.$refs["formItem"].validate((valid) => {
        if (valid) {
          if (this.operate === "add") {
            // 如果当前登录人为超级管理员
            if (this.userCode !== "admin") {
              this.formItem.groupId = this.groupId;
              this.formItem.companyId = this.passcompanyId;
            } else {
              this.formItem.groupId = this.formItem.groupData;
              this.formItem.companyId = this.formItem.companyData;
            }
            let form = JSON.parse(JSON.stringify(this.formItem));
            // 统一平台激活用户
            if (this.appCode) {
              form["appCode"] = this.appCode;
              form["type"] = 1;
            }

            // 新增时将机构与职级信息关联
            // let orgId = '',
            //     orgName = '';
            // dgTree(this.orgTree.tree, 'children', item => {
            //     if (item.orgCode === this.formItem.orgCode) {
            //         orgId = item.orgId;
            //         orgName = item.orgName;
            //     }
            // });
            // let obj = {
            //     orgId: orgId,
            //     orgName: orgName,
            //     dutyId: Array.isArray(this.formItem.dutys)? this.formItem.dutys[0] : this.formItem.dutys
            // }
            // this.orgForm.OrgLinks = [obj];
            // console.log(10);
            // console.log(this.orgForm.OrgLinks)
            this.addUser(form);
          } else if (this.operate === "edit") {
            // 讲所属公司处理成字符串的形式
            this.formItem.groupId = this.formItem.groupData;
            this.formItem.companyId = this.formItem.companyData;
            if (!this.isSaveUserInfo) {
              if (this.orgForm.OrgLinks[0]) {
                dgTree(this.orgTree.tree, "children", (item) => {
                  if (item.orgCode === this.orgForm.OrgLinks[0].orgCode) {
                    this.orgForm.OrgLinks[0].orgId = item.orgId;
                  }
                });
              }
              this.orgLinkConfirm(true);
            }
            let _flag = false;
            this.formItem.dutys.forEach((item) => {
              if (item === "") {
                _flag = true;
              }
            });
            if (_flag) {
              this.formItem.dutys = [];
            }
            this.editUser(this.formItem);
          }
        }
      });
    },
    //  找父节点
    dgPid(tree, id, cb) {
      dgTree(tree, "", (item) => {
        if (item.id === id) {
          cb(item);
          if (item.pId) {
            this.dgPid(tree, item.pId, cb);
          }
        }
      });
    },
    //  选择图片
    headerInputClick() {
      this.$refs.avatarInput.click();
    },
    //  读取图片
    loadImg() {
      // 获取文件
      let file = this.$refs.avatarInput.files[0];
      // 创建读取文件的对象
      let reader = new FileReader();
      // 创建文件读取相关的变量
      let imgFile;
      // 为文件读取成功设置事件
      reader.onload = (e) => {
        imgFile = e.target.result;
        this.headerSrc = imgFile;
      };
      // 正式读取文件
      reader.readAsDataURL(file);
    },
    getRoles(val) {
      return this.store
        .dispatch("system/rolesManage/list", {
          companyId: val,
        })
        .then((res) => {
          if (res.code === "0") {
            this.roleList = res.data;
            if (this.operate1 === "index") {
              let roleArr = [];
              for (let i = 0; i < this.roleList.length; i++) {
                for (let a = 0; a < this.qrRole.length; a++) {
                  if (this.roleList[i].roleId === this.qrRole[a]) {
                    roleArr.push(this.roleList[i]);
                  }
                }
              }
              this.roleList = roleArr;
            }
            this.getEntryListData(val)
          } else {
            this.$message.error(res.message);
          }
        });
    },
    //判断长度
    charLength(val) {
      var len = 0;
      for (var i = 0; i < val.length; i++) {
        var a = val.charAt(i);
        if (a.match(/[^\x00-\xff]/gi) != null) {
          len += 3;
        } else {
          len += 1;
        }
      }
      return Number(len);
    },
    getOrgDutyInfo(companyId) {
      let that = this;
      let _userId = this.formItem.userId === ''?'lull': this.formItem.userId;
      return that.axios
        .get(
          "pass/v1/sysuserorgdutys/like/?userId=" +
            _userId +
            "&pageNum=1&pageSize=1000"
        )
        .then((res) => {
          if (res.code === "0") {
            this.orgForm.OrgLinks = res.data.list;
            for (let org of this.orgForm.OrgLinks) {
              dgTree(this.orgTree.tree, "children", (item) => {
                if (item.orgId === org.orgId) {
                  org["orgName"] = item.orgName;
                  org["orgCode"] = item.orgCode;
                }
              });
              org.orgCode === this.formItem.orgCode
                ? (org.label = true)
                : (org.label = false); //标记与用户信息相同的数据
            }
            if (this.orgForm.OrgLinks.length > 1) {
              for (
                let index = 0;
                index < this.orgForm.OrgLinks.length;
                index++
              ) {
                const element = this.orgForm.OrgLinks[index];
                if (element.orgCode === this.formItem.orgCode) {
                  if (index !== 0) {
                    this.orgForm.OrgLinks.unshift(element);
                    this.orgForm.OrgLinks.splice(index + 1, 1);
                  }
                }
              }
            }
          } else {
            this.$message.error(res.message);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 添加新的机构-职级-用户关联
    addOrgLink() {
      let obj = {
        id: "",
        orgId: "",
        orgName: "",
        dutyId: "",
        pId: "",
      };
      this.orgForm.OrgLinks.push(obj);
    },
    removeOrgLink(obj, index) {
      if (obj.id == "") {
        this.orgForm.OrgLinks.splice(index, 1);
      } else {
        let orgCode = this.formItem.orgCode;
        if (orgCode === obj.orgCode) {
          this.$message.error("当前节点无法删除");
          return;
        }
        this.axios
          .delete("pass/v1/sysuserorgdutys/" + obj.id)
          .then((res) => {
            if (res.code === "0") {
              this.$message.success("已删除");
              this.getOrgDutyInfo();
              this.$emit("updateOrgDutyLink");
            } else {
              this.$message.error(res.message);
            }
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
          // this.orgForm.OrgLinks = [];
        })
        .catch((_) => {});
    },
    orgLinkConfirm(flag) {
      let that = this;
      let ggfunciton = function () {
        let i = 0;
        if (that.orgForm.OrgLinks.length > 0) {
          for (let item of that.orgForm.OrgLinks) {
            let params = {
              userId: that.formItem.userId,
              dutyId: item.dutyId,
              orgId: item.orgId,
            };
            i++;
            // 编辑模式
            that.isSaveUserInfo = true;
            if (item.id && item.id !== "") {
              that.axios
                .put("pass/v1/sysuserorgdutys/" + item.id, params)
                .then((res) => {
                  if (res.code === "0") {
                    if (i === that.orgForm.OrgLinks.length) {
                      that.$message.success("保存成功");
                      that.$emit("updateOrgDutyLink");
                      that.dialogFormVisible = false;
                    }
                  } else {
                    that.$message.error(res.message);
                    that.dialogFormVisible = false;
                  }
                })
                .catch((err) => {
                  console.log(err);
                });
            } else {
              // 新增模式
              that.axios
                .post("pass/v1/sysuserorgdutys/", params)
                .then((res) => {
                  if (res.code === "0") {
                    if (i === that.orgForm.OrgLinks.length) {
                      that.$message.success("保存成功");
                      that.$emit("updateOrgDutyLink");
                      that.dialogFormVisible = false;
                    }
                  } else {
                    that.$message.error(res.message);
                    that.dialogFormVisible = false;
                  }
                })
                .catch((err) => {
                  console.log(err);
                });
            }
          }
        } else {
          // that.$message.error("至少需要一个关联");
          that.$emit("updateOrgDutyLink");
          that.dialogFormVisible = false;
        }
      };
      if (flag) {
        ggfunciton();
      } else {
        that
          .$confirm("确认保存？")
          .then((_) => {
            ggfunciton();
          })
          .catch((_) => {
            that.$message.info("已取消保存");
          });
      }
    },
    orgLinkCancel() {
      this.$confirm("确认关闭？")
        .then((_) => {
          this.dialogFormVisible = false;
          // this.orgForm.OrgLinks = [];
        })
        .catch((_) => {});
    },
    changeDuty(val) {
      //关联弹窗里面修改岗位
      if (val.orgCode === this.formItem.orgCode) {
        this.formItem.dutys = [val.dutyId];
      }
    },
    //身份证改变事件（孕妇）
    IDCardChange(val) {
      //判断身份证长度
      if (val.length == 18) {
        //获取计算后出生日期
        var birthDateStr = this.getBirthDate(val);
        //设置出生日期
        this.formItem.birthDate = birthDateStr;
        //获取当前的日期
        var nowDateStr = this.getNowDate();
        //获取计算后年龄(两个日期之间)
        var age = this.getAge(birthDateStr, nowDateStr);
        //设置年龄
        this.formItem.age = age;
      }
    },

    //根据身份证号计算出生日期
    getBirthDate(IDCard) {
      //获取身份证号的年、月、日
      var year = IDCard.substring(6, 10);
      var month = IDCard.substring(10, 12);
      var day = IDCard.substring(12, 14);
      //拼接成出生日期
      var birthDate = year + "-" + month + "-" + day;
      return birthDate;
    },

    //根据两个日期计算年龄（是否过生日）
    getAge(startDateStr, endDateStr) {
      //计算两个日期相差多少年
      var startDate = new Date(startDateStr);
      var endDate = new Date(endDateStr);
      var yearNum = endDate.getFullYear() - startDate.getFullYear();
      //获取两个日期（月+日）部分
      var sStr = startDateStr.substring(5, 10);
      var eStr = endDateStr.substring(5, 10);
      //判断两个日期大小
      //判断是否过生日
      if (new Date(sStr) <= new Date(eStr)) {
        return yearNum + 1;
      } else {
        return yearNum;
      }
    },

    ///获取当前日期
    getNowDate() {
      var d = new Date();
      var year = d.getFullYear();
      var month = d.getMonth() + 1;
      var day = d.getDate();
      var dateStr =
        year + "-" + this.getFormatDate(month) + "-" + this.getFormatDate(day);
      return dateStr;
    },

    //格式化日期的月份或天数的显示（小于10，在前面增加0）
    getFormatDate(value) {
      if (value == undefined || value == "") {
        return "";
      }
      var str = value;
      if (parseInt(value) < 10) {
        str = "0" + value;
      }
      return str;
    },
    throttle(func, delay) {
      var prev = Date.now();
      return function () {
        var context = this;
        var args = arguments;
        var now = Date.now();
        if (now - prev >= delay) {
          func.apply(context, args);
          prev = Date.now();
        }
      };
    },
    getEntryListData(val) {
      this.searchForm.companyId = val;
      return this.axios
        .get("pass/v1/sysappclients/like/", { params: this.searchForm })
        .then((response) => {
          let res = response.data;
          if (response.succeed) {
            this.EntryListData = res.list;
            for(let k =0; k < this.EntryListData.length; k++) {
              let entryList = this.EntryListData[k];
              for(let j = 0; j < this.roleList.length; j ++) {
                let roleList = this.roleList[j];
                if(entryList.appId === roleList.appId) {
                  roleList.appName = entryList.appName;
                }
              }
            }
          } else {
            this.$message.error(response.message);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    }
  },
};
</script>

<style lang="less" scoped>
.sui-slider {
  display: block;

  .sui-slider-main {
    display: block;
    position: absolute;
    top: 0px;
    right: 0px;
    z-index: 1904;
    width: 800px;
    height: 100%;
    box-shadow: rgb(51, 51, 51) 0px 0px 8px;
    background-color: rgb(255, 255, 255);
    overflow: auto;

    .oa-usersManage-header {
      width: 100px;
      height: 100px;
      vertical-align: middle;
      margin: 0 auto;
      cursor: pointer;
      position: relative;
      bottom: 10px;
    }

    /deep/ .el-select__tags-text {
      text-overflow: ellipsis;
      max-width: 68px;
      display: inline-block;
      overflow: hidden;
    }

    /deep/ .el-select .el-tag__close.el-icon-close {
      top: -6px;
    }

    /deep/ .el-select__tags input {
      position: absolute;
    }
  }

  .oa-usersManage-header > img {
    width: 55px;
    height: 55px;
    vertical-align: middle;
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    border-radius: 50%;
  }

  .user_upload .ivu-upload {
    height: 50px;
  }

  .file_btn_upload {
    margin-top: -5px;
  }

  .content {
    height: 50px;
    text-align: center;
  }

  .file_upload > div {
    width: 100%;
    height: 100%;
  }

  .file_btn_upload .hide {
    width: 120px;
    height: 30px;
    opacity: 0;
    filter: alpha(opacity=0);
    position: absolute;
    display: none;
    z-index: 22;
  }

  .img_holder {
    display: inline-block;
    width: 55px;
    height: 55px;
    cursor: pointer;
  }

  .img_box {
    position: relative;
    height: 55px;
    top: -20px;
    display: inline-block;
    vertical-align: top;
    border: 1px transparent dashed;
    padding: 12px;
    box-shadow: 2px 2px 10px #ccc;
  }

  //   /deep/ .el-select__tags {
  //     white-space: nowrap;
  //     flex-wrap: nowrap;
  //   }
  //   /deep/ .el-select__tags-text {
  //     max-width: 110px;
  //     display: inline-block;
  //     overflow: hidden;
  //     text-overflow: ellipsis;
  //     white-space: nowrap;
  //     flex-wrap: nowrap;
  //   }
  //   /deep/ .el-select .el-tag__close.el-icon-close {
  //       top: -5px;
  //   }
  .showLen {
    position: absolute;
    bottom: -20px;
    color: #37c167;
    z-index: 80;
    left: 0;
  }

  .el-form-item__error {
    background: #fff !important;
    z-index: 81;
  }
}

.expireDays {
  width: 89%;
  margin-right: 2%;
}

.el-input .el-input--small .el-input--suffix {
  height: 28px !important;
}

.el-input__inner {
  height: 28px !important;
}

.el-message .el-message--error {
  z-index: 3100 !important;
}

.el-message .el-message--success {
  z-index: 3100 !important;
}
</style>

<style>
.el-select-dropdown.is-multiple .el-select-dropdown__item.selected span {
  text-overflow: ellipsis;
  max-width: 85%;
  display: inline-block;
  overflow: hidden;
}

.el-select-dropdown.is-multiple .el-select-dropdown__item.selected span:hover {
  overflow: visible;
}
</style>
