<template>
  <div class="organizManage-main userManage">
    <div class="organizManage-mainLeft">
      <!-- 下拉框切换公司 -->
      <!-- <div class="_refresh3" v-if="currentUserCompany !== '' && currentUserCompany.length > 1">
                <el-dropdown
                    trigger="click"
                    @command="changeThing"
                >
                    <span class="el-dropdown-link">
                        {{companyName}}<i class="el-icon-arrow-down el-icon--right"></i>
                    </span>
                    <el-dropdown-menu slot="dropdown">
                        <div v-for="item in currentUserCompany" :key="item.id">
                            <el-dropdown-item :command="item">{{item.companyName}}</el-dropdown-item>
                        </div>
                    </el-dropdown-menu>
                </el-dropdown>
            </div> -->
      <div class="public-function-div">
        机构树
        <el-button
          type="success"
          @click="setCheckedNodes"
          size="small"
          class="refresh"
          >展开</el-button
        >
        <el-button
          type="success"
          @click="setCheckedKeys"
          size="small"
          class="refresh2"
          >收起</el-button
        >
        <!-- <el-select v-model="selectCompany" filterable class="_refresh3" size='small' placeholder="请选择所属公司" @change="changeThing" v-show="currentUserCompany.length > 1">
                  <el-option
                    v-for="item in currentUserCompany"
                    :key="item.id"
                    :label="item.companyName"
                    :value="item.id">
                  </el-option>
                </el-select> -->
        <!-- <div class="searchClass">
                  <i class="el-icon-search"></i>
                </div> -->
        <!-- <el-input v-model="form.name" placeholder="请输入名称"
                    suffix-icon="el-icon-search"></el-input> -->
      </div>
      <el-tree
        ref="orgTree"
        :data="orgTree"
        :props="defaultProps"
        highlight-current
        node-key="id"
        v-loading="treeLoading"
        @node-click="nodeClick"
        :expand-on-click-node="true"
        :filter-node-method="filterOrgTree"
        :style="{ height: treeHeight + 'px' }"
      >
      </el-tree>
    </div>
    <div class="organizManage-mainRight">
      <div class="public-function-div">用户列表</div>
      <div class="post-m">
        <el-form class="userModal" label-width="40px">
          <el-row>
            <el-col :span="6">
              <el-form-item label="账户">
                <el-input
                  style="width: 100%"
                  v-model="tableParams.form.userCode"
                  clearable
                  placeholder="请输入"
                  size="small"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="姓名">
                <el-input
                  style="width: 100%"
                  v-model="tableParams.form.userName"
                  clearable
                  placeholder="请输入"
                  size="small"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="手机">
                <el-input
                  style="width: 100%"
                  v-model="tableParams.form.mobile"
                  clearable
                  placeholder="请输入"
                  size="small"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="机构">
                <el-select
                  style="width: 100%"
                  v-model="tableParams.form.orgCode"
                  @change="changeOrg"
                  filterable
                  clearable
                  :filter-method="filterSelect1"
                  placeholder="请选择机构"
                  size="small"
                >
                  <el-option
                    ref="orgselect"
                    :value="tableParams.form.orgCode"
                    :label="tableParams.form.orgName"
                    style="height: auto; padding: 0px"
                  >
                    <el-tree
                      :data="orgTree"
                      highlight-current
                      node-key="id"
                      show-checkbox
                      check-strictly
                      check-on-click-node
                      ref="org1tree"
                      :props="defaultProps"
                      :filter-node-method="filterOrgTree"
                      @check-change="handleCheckChange1"
                      @node-collapse="nodeUpdate2"
                      @node-expand="nodeUpdate1"
                    >
                    </el-tree>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div style="text-align: right; margin-bottom: 10px">
          <!-- <el-checkbox
                        v-model="icoreFilterFlag"
                        style="float:left;margin-top: 9px;"
                    >过滤</el-checkbox> -->
          <el-button
            icon="el-icon-search"
            type="primary"
            size="small"
            v-privilege="activeMenu + 'SEARCH'"
            @click="search"
            >查询</el-button
          >
          <el-button
            icon="el-icon-edit"
            type="primary"
            size="small"
            v-privilege="activeMenu + 'EDIT'"
            @click="userMigrate"
            >移动用户</el-button
          >
          <el-button
            size="small"
            type="primary"
            icon="el-icon-circle-plus-outline"
            v-privilege="activeMenu + 'ADD'"
            @click="operateClick('add', {})"
            >新增</el-button
          >
          <!-- 批量添加 -->
          <el-form
            :model="form"
            ref="form"
            :rules="rules"
            label-width="80px"
            :inline="true"
            size="normal"
            style="display: inline-block"
          >
            <el-upload
              ref="upload"
              :action="uploadUrl"
              :limit="1"
              :before-upload="beforeUpload"
              :headers="token"
              accept=".xls"
              class="up-class"
              :on-success="uploadSuccess"
              :show-file-list="false"
              :auto-upload="true"
            >
              <el-button
                slot="trigger"
                size="small"
                type="primary"
                class="el-icon-plus el-icon-upload"
                >批量新增</el-button
              >
            </el-upload>
          </el-form>
          <!-- <el-button type="warning" size="small" @click="delAllPost">批量删除</el-button> -->
        </div>
        <el-table
          ref="userTable"
          individual-columns="individual-vue-table-columns"
          :individual-info="individualInfo"
          drag-column="individual-vue-table"
          @icoreFilterChange="icoreFilterChange"
          :icore-filter-flag="icoreFilterFlag"
          v-loading="tabLoading"
          border
          :height="tableHeight > 400 ? tableHeight : 400"
          highlight-current-row
          @selection-change="handleSelectionChange"
          :data="table.list"
        >
          <el-table-column type="selection" width="55" align="center">
          </el-table-column>
          <el-table-column
            type="index"
            label="序号"
            fixed="left"
            align="center"
          ></el-table-column>
          <el-table-column
            :show-overflow-tooltip="true"
            prop="userCode"
            label="账户"
            align="center"
            min-width="120"
          ></el-table-column>
          <el-table-column
            :show-overflow-tooltip="true"
            prop="userName"
            label="姓名"
            align="center"
            width="120"
          ></el-table-column>
          <!-- <el-table-column :show-overflow-tooltip="true" label="部门" min-width="100"></el-table-column> -->
          <!-- <el-table-column :show-overflow-tooltip="true"
                           prop="duty"
                           label="职务"
                           :filter-method="filterColumn"
                           min-width="100"></el-table-column> -->
          <el-table-column
            :show-overflow-tooltip="true"
            prop="mobile"
            label="手机"
            align="center"
            min-width="120"
          ></el-table-column>
          <!-- <el-table-column :show-overflow-tooltip="true"
                           prop="degree"
                           align="center"
                           label="文化程度"
                           min-width="80"></el-table-column> -->
          <el-table-column
            :show-overflow-tooltip="true"
            prop="orgName"
            align="center"
            label="机构"
            width="150"
          ></el-table-column>
          <!-- <el-table-column :show-overflow-tooltip="true"
                           prop="major"
                           align="center"
                           label="专业"
                           min-width="80"></el-table-column> -->
          <el-table-column
            :show-overflow-tooltip="true"
            align="center"
            type="noFilter"
            label="在职状态"
            width="80"
          >
            <template slot-scope="scope">
              <span
                class="color-primary"
                v-if="
                  scope.row.sysUserLogin !== null &&
                  scope.row.sysUserLogin.leave === '0'
                "
                >在职</span
              >
              <span
                class="color-danger"
                v-else-if="
                  scope.row.sysUserLogin !== null &&
                  scope.row.sysUserLogin.leave === '1'
                "
                >离退</span
              >
              <span
                class="color-danger"
                v-else-if="
                  scope.row.sysUserLogin !== null &&
                  scope.row.sysUserLogin.leave === '2'
                "
                >离休</span
              >
              <span
                class="color-danger"
                v-else-if="
                  scope.row.sysUserLogin === null ||
                  scope.row.sysUserLogin.leave === null
                "
              ></span>
            </template>
          </el-table-column>
          <el-table-column
            :show-overflow-tooltip="true"
            type="noFilter"
            label="状态"
            width="80"
            align="center"
          >
            <template slot-scope="scope">
              <span class="color-danger" v-if="scope.row.status === '0'"
                >停用</span
              >
              <span
                class="color-primary"
                v-else-if="
                  scope.row.status === '1' &&
                  scope.row.sysUserLogin &&
                  scope.row.sysUserLogin.status === '0'
                "
                >启用</span
              >
              <span
                class="color-danger"
                v-else-if="
                  scope.row.status === '1' &&
                  scope.row.sysUserLogin &&
                  scope.row.sysUserLogin.status === '1'
                "
                >锁定</span
              >
              <span
                class="color-danger"
                v-else-if="
                  scope.row.status === '1' &&
                  scope.row.sysUserLogin &&
                  scope.row.sysUserLogin.status === '2' &&
                  scope.row.sysUserLogin.expireStatus === '0'
                "
                >密码过期</span
              >
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            type="noFilter"
            fixed="right"
            width="105"
          >
            <template slot-scope="scope">
              <!-- <el-dropdown
                                @command="handleCommand"
                                :show-timeout="50"
                                style="margin-left: 5px;"
                            >
                                <span
                                    class="el-dropdown-link"
                                    @click.stop
                                >
                                    操作<i class="el-icon-arrow-down"></i>
                                </span>
                                <el-dropdown-menu slot="dropdown">
                                    <el-dropdown-item
                                        :command="['edit', scope.row]"
                                        v-privilege="activeMenu + 'EDIT'"
                                    >修改</el-dropdown-item>
                                    <el-dropdown-item
                                        :command="['czmm', scope.row]"
                                        v-privilege="activeMenu + 'RESETPASSWORD'"
                                    >重置密码</el-dropdown-item>
                                    <el-dropdown-item
                                        :command="['jcsd', scope.row]"
                                        v-privilege="activeMenu + 'UNLOCK'"
                                    >解除锁定</el-dropdown-item>
                                    <el-dropdown-item
                                        :command="['tyqy', scope.row]"
                                        v-privilege="activeMenu + 'DEACTIVATEENABLE'"
                                    >{{!Number(scope.row.status) ? '启用':'停用'}}</el-dropdown-item>
                                </el-dropdown-menu>
                            </el-dropdown> -->
              <el-dropdown
                split-button
                size="mini"
                type="primary"
                trigger="click"
                @click="handleCommand(['edit', scope.row])"
                @command="handleCommand"
                v-privilege="activeMenu + 'EDIT'"
              >
                修改
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item
                    :command="['czmm', scope.row]"
                    v-privilege="activeMenu + 'RESETPASSWORD'"
                    >重置密码</el-dropdown-item
                  >
                  <el-dropdown-item
                    :command="['jcsd', scope.row]"
                    v-privilege="activeMenu + 'UNLOCK'"
                    >解除锁定</el-dropdown-item
                  >
                  <el-dropdown-item
                    :command="['jh', scope.row]"
                    v-privilege="activeMenu + 'activation'"
                    v-if="Number(scope.row.status)"
                    >激活</el-dropdown-item
                  >
                  <el-dropdown-item
                    :command="['tyqy', scope.row]"
                    v-privilege="activeMenu + 'DEACTIVATEENABLE'"
                    >{{
                      !Number(scope.row.status) ? "启用" : "停用"
                    }}</el-dropdown-item
                  >
                  <el-dropdown-item
                    :command="['del', scope.row]"
                    v-privilege="activeMenu + 'DELETE'"
                    style="color: #ff474e"
                    >删除</el-dropdown-item
                  >
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <div class="foot-style">
          <el-pagination
            @size-change="pageSizeChange"
            @current-change="pageCurrentChange"
            :current-page="tableParams.form.pageNum"
            :page-sizes="[10, 20, 50, 100, 200]"
            :page-size="tableParams.form.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="tableParams.page.total"
          >
          </el-pagination>
        </div>
      </div>
    </div>

    <div
      is="usersAddAndEdit"
      v-if="userModal.show"
      :operate="operate"
      :item="table.item"
      :passcompanyId="companyId"
      @on-then="userModalThen"
      @on-close="userModalClose"
      @updateOrgDutyLink="updateOrgDutyLink"
    ></div>

    <!-- 分配岗位 -->
    <el-dialog
      :title="'岗位选择'"
      :visible.sync="postModal.show"
      width="680px"
      center
    >
      <el-table
        ref="postTable"
        v-loading="postModal.loading"
        border
        :height="400"
        highlight-current-row
        :data="postModal.list"
        @selection-change="postSelectChange"
      >
        <el-table-column
          type="selection"
          align="center"
          fixed="left"
        ></el-table-column>
        <el-table-column
          :show-overflow-tooltip="true"
          prop="postCode"
          label="岗位编码"
          min-width="100"
        ></el-table-column>
        <el-table-column
          :show-overflow-tooltip="true"
          prop="postName"
          label="岗位名称"
          min-width="100"
        ></el-table-column>
        <el-table-column
          :show-overflow-tooltip="true"
          prop="cate"
          label="岗位类别"
          min-width="80"
        ></el-table-column>
        <!-- <el-table-column :show-overflow-tooltip="true" prop="level" label="岗位级别"
        min-width="150"></el-table-column> -->
        <el-table-column
          :show-overflow-tooltip="true"
          prop="postDesc"
          label="职责描述"
          min-width="150"
        ></el-table-column>
        <el-table-column label="岗位类型" prop="postType" min-width="150">
          <template slot-scope="scope">
            <template v-for="item in postModal.items">
              <span
                :key="item.postId"
                v-if="item.postId === scope.row.postId && item.postType === '1'"
                >主岗位</span
              >
              <span
                :key="item.postId"
                v-if="item.postId === scope.row.postId && item.postType === '2'"
                >副岗位</span
              >
              <el-button
                :key="item.postId + 'btn'"
                v-if="item.postId === scope.row.postId && item.postType === '2'"
                @click="postTypeMain(item)"
                size="mini"
                :style="{ padding: '3px 6px' }"
                >设为主岗位</el-button
              >
            </template>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="postModal.show = false" size="small"
          >取 消</el-button
        >
        <el-button
          type="primary"
          :loading="postModal.okLoading"
          @click="postUserOk"
          size="small"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <icore-individual
      uiId="pangguoqianperf"
      indexClass="individual-index"
    ></icore-individual>
    <el-dialog
      :title="'移动用户'"
      :visible.sync="migrateVisible"
      :before-close="migrateCancel"
      center
    >
      <div style="text-align: center; margin: 20px 30px">
        <el-form>
          <el-row :gutter="30">
            <el-col :span="12">
              <el-form-item label="原始机构">
                <el-input
                  type="textarea"
                  autosize
                  placeholder="请输入内容"
                  :disabled="true"
                  v-model="migrate.orgList2"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="转移目标机构">
                <el-select
                  v-model="migrate.orgCode"
                  @change="changeOrg"
                  filterable
                  clearable
                  :filter-method="filterSelect2"
                  placeholder="请选择机构"
                  size="small"
                  style="height: auto"
                >
                  <el-option
                    :value="migrate.orgCode"
                    :label="migrate.orgName"
                    style="height: auto; padding: 0px"
                  >
                    <el-tree
                      :data="orgTree"
                      highlight-current
                      node-key="id"
                      show-checkbox
                      check-strictly
                      check-on-click-node
                      ref="org2tree"
                      :props="defaultProps"
                      :default-checked-keys="[]"
                      :filter-node-method="filterOrgTree"
                      @check-change="handleCheckChange"
                    >
                    </el-tree>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-button
          style="margin-top: 20px"
          type="primary"
          @click="migrateSave"
          size="small"
          >保存</el-button
        >
        <el-button style="margin-top: 20px" @click="migrateCancel" size="small"
          >取消</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import store from "@/store/index.js";
import usersAddAndEdit from "./usersAddAndEdit.vue";
import { dgTree } from "@/utils/util.js";
import checkPermission from "@/config/permission.js";
import { getCookie } from "@/utils/util.js";
export default {
  components: {
    usersAddAndEdit,
  },
  data() {
    return {
      currentUserCompany: JSON.parse(
        window.top.localStorage.getItem("companys")
      ),
      orgTree: [],
      treeLoading: false,
      activeMenu: "",
      companyId: window.top.localStorage.getItem("companyId"),
      companyName: "",
      setFilterCurrent: null,
      icoreFilterFlag: false,
      filterText: "",
      store,
      treeHeight: 600,
      tableHeight: 600,
      operate: "detail",
      tabLoading: false,
      multipleSelection: [], // 复选框选择数据列表
      migrate: {
        orgList1: [],
        orgList2: "",
        orgCode: "",
        orgName: "",
      },
      migrateVisible: false, // 移动用户编辑区显示
      table: {
        list: [],
        //  选中项
        items: [],
        item: {},
      },
      tableParams: {
        form: {
          orgCode: "",
          orgName: "",
          pageNum: 1,
          pageSize: 20,
          companyId: "",
        },
        //  返回分页数据
        page: {
          total: 0,
        },
      },
      //  modal
      userModal: {
        show: false,
      },
      //  岗位弹窗
      postModal: {
        show: false,
        userId: "",
        //  岗位列表
        list: [],
        //  中间表列表
        postUserList: [],
        //  选中岗位
        items: [],
        loading: false,
        okLoading: false,
      },
      filterStatus: false,
      individualInfo: {},
      activeRow: {},
      userStatus: "", // 用户状态筛选
      userStatusList: [
        {
          value: 1,
          label: "启用",
        },
        {
          value: 2,
          label: "停用",
        },
        {
          value: 3,
          label: "锁定",
        },
        {
          value: 4,
          label: "密码过期",
        },
      ],
      role: "", // 用户角色筛选
      userRoles: [], // 用户已拥有的关联角色信息
      password: "",
      //批量新增
      importData: {         //参数
        type: 'http://icore-paas-test.steerinfo.com/icore.icp.web/pass/v1/sysusers/batchImportByExcel'
      },
      uploadUrl: 'icore.icp.web/pass/v1/sysusers/batchImportByExcel',   //地址
      token: {     //请求头
        Authorization: null,
      }
    };
  },
  watch: {
    // filterText (val) {
    //     this.$refs.orgTree.filter(val);
    // },
    "tableParams.form.orgCode": {
      immediate: false,
      handler: function (n, o) {
        if (n === "") {
          this.$refs.org1tree.setCheckedNodes([]);
        }
      },
    },
    "migrate.orgCode": {
      immediate: false,
      handler: function (n, o) {
        if (n === "") {
          this.$refs.org2tree.setCheckedNodes([]);
        }
      },
    },
    // icoreFilterFlag (val) {
    //     if (this.icoreFilterFlag === false) {
    //         this.tableParams.page.total = this.tableParams.page.totalBack;
    //     }
    //     if (val) {
    //         this.setFilterCurrent = this.tableParams.form.pageNum;
    //     }
    // }
    // table: {
    //     deep: true,
    //     handler: function (newVal,oldVal){
    //         this.tableParams.page.total = this.tableParams.page.totalBack;
    //     }
    // }
  },
  computed: {
    //  菜单树数据
    // orgTree () {
    //     let tree = this.store.state.system.organizManage.tree;
    //     //
    //     dgTree(tree, 'children', item => {
    //         if ('children' in item && item.children.length < 1) {
    //             delete item.children;
    //         }
    //     });
    //     return tree;
    // },
    //  树配置
    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;
    },
  },
  created() {
    this.activeMenu = window.top.localStorage.getItem("activeMenu");
    this.getPwdValid();
  },
  mounted() {
    if (this.companyId !== "" && this.companyId !== null) {
      this.companyName = this.currentUserCompany.find(
        (x) => x.id === this.companyId
      ).companyName;
    }
    this.tableParams.form.companyId = this.companyId;
    this.initData(this.companyId);
    //  设置树区域高度
    this.treeHeight = this.getTreeHeight(this.$refs["orgTree"].$el) - 50;
    this.tableHeight = this.getTableHeight(this.$refs["userTable"].$el) - 80;
    this.$nextTick(() => {
      this.icoreFilterFlag = true;
    });
    // 批量添加
    this.token.Authorization = "Bearer " + getCookie("accessToken");   //从cookie里获取token

  },
  methods: {
    checkPermission,
    async initData(val) {
      this.treeLoading = true;
      this.tabLoading = true;
      //  查询机构树
      await this.store
        .dispatch("system/organizManage/tree", val)
        .then((res) => {
          if (res.code === "0") {
            this.store.commit("system/organizManage/tree", res.data);
            this.orgTree = res.data;
          } else {
            this.$message.error(res.message);
          }
          this.treeLoading = false;
        });
      this.getUser(this.tableParams.form);
    },
    // 获取当前密码策略
    getPwdValid() {
      this.axios
        .get("pass/v1/syspwdpolicys/getExecutingPwdPolicy")
        .then((res) => {
          if (res.code === "0") {
            this.password = res.data.password;
          } else {
            this.$message.error(res.message);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 改变下拉款数据时，加载相应数据
    changeThing(res) {
      this.initData(res.id);
      this.companyName = res.companyName;
      this.companyId = res.id;
      // 清除右侧数据
      (this.tableParams = {
        form: {
          orgCode: "",
          orgName: "",
          pageNum: 1,
          pageSize: 20,
          companyId: res.id,
        },
        //  返回分页数据
        page: {
          total: 0,
        },
      }),
        this.getUser(this.tableParams.form);
    },
    // 选择机构下拉值筛选
    filterSelect1(val) {
      this.$refs.org1tree.filter(val);
    },
    // 迁移机构下拉值筛选
    filterSelect2(val) {
      this.$refs.org2tree.filter(val);
    },
    //  取用户列表
    getUser(form, status) {
      this.tabLoading = true;
      this.store.dispatch("system/usersManage/list", form).then((res) => {
        if (res.code === "0") {
          this.table.list = res.data.list;
          for (let a = 0; a < this.table.list.length; a++) {
            this.table.list[a].orgName = this.getOrgName(
              this.orgTree,
              this.table.list[a].orgCode
            );
          }
          this.tableParams.page.total = res.data.total;
          this.tableParams.page.totalBack = res.data.total;
          let index = 0;
          for (let i = 0; i < this.table.list.length; i++) {
            if (this.table.list[i].userId === this.activeRow.userId) {
              index = i;
            }
          }
          this.$refs["userTable"].setCurrentRow(this.table.list[index]);
          this.tabLoading = false;
          // this.$nextTick(() => {
          //     let ss = document.createElement('div');
          //     ss.innerHTML = '筛选';
          //     ss.style = 'text-align: center;'
          //     this.$refs.userTable.$el.getElementsByClassName('el-table__fixed')[0].getElementsByTagName('td')[0].appendChild(ss);
          // });
        } else {
          this.$message.error(res.message);
          this.tableParams.form.pageNum = 1;
          this.tableParams.page.total = 0;
          this.tabLoading = false;
        }
      });
    },
    // 选择一或多行
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 移动用户
    userMigrate() {
      if (this.multipleSelection.length >= 1) {
        this.migrateVisible = true;
        for (let i = 0; i < this.multipleSelection.length; i++) {
          let id = this.multipleSelection[i].userId;
          // console.log(this.migrate.orgList1.indexOf(this.multipleSelection[i].orgName))
          if (
            this.migrate.orgList1.indexOf(this.multipleSelection[i].orgName) ===
            -1
          ) {
            this.migrate.orgList1.push(this.multipleSelection[i].orgName);
          }
        }
        this.migrate.orgList2 = this.migrate.orgList1.join("\n");
      } else {
        this.$message({
          type: "warning",
          message: "至少选择一个用户进行移动操作!",
        });
      }
    },
    migrateSave() {
      let that = this;
      if (this.migrate.orgCode) {
        this.$confirm("您确定要对已选用户进行机构转移吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            for (let i in this.multipleSelection) {
              let id = this.multipleSelection[i].userId;
              let data = new FormData();
              data.append("orgCode", this.migrate.orgCode);
              data.append("companyId", this.companyId);
              this.store
                .dispatch("system/usersManage/editUser", { id: id, form: data })
                .then((res) => {
                  if (res.code === "0") {
                    // let index = this.table.list.map(item => item.userId).indexOf(id);
                    // this.table.list.splice(index, 1);
                    // 移动用户机构清空角色
                    this.clearUserRole(id);
                    this.getUser(this.tableParams.form);
                    this.$message.success("移动成功");
                    this.migrateVisible = false;
                    this.migrate.orgCode = "";
                    this.migrate.orgName = "";
                    this.tableParams.form.pageNum = 1;
                    this.tableParams.form.pageSize = 20;
                    this.migrate.orgList1 = [];
                    this.$nextTick(() => {
                      this.$refs.org2tree.setCheckedKeys([]);
                    });
                  } else {
                    this.$message.error(res.message);
                  }
                });
            }
          })
          .catch(() => {
            this.migrateVisible = false;
            this.migrate.orgCode = "";
            this.migrate.orgName = "";
            this.$message.info("已取消移动");
            this.migrate.orgList1 = [];
            this.$nextTick(() => {
              this.$refs.org2tree.setCheckedKeys([]);
            });
          });
      } else {
        this.$message({
          type: "warning",
          message: "转移目标机构不能为空!",
        });
      }
    },
    // 清空角色
    async clearUserRole(id) {
      let that = this;
      await that
        .getUserRole(id)
        .then((res) => {
          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);
                });
            }
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 获取当前用户角色
    getUserRole(userid) {
      let that = this;
      const promise = that.axios
        .get(
          "pass/v1/sysuserroles/?userId=" + userid + "&pageNum=1&pageSize=100"
        )
        .then((res) => {
          if (res) {
            that.userRoles = res.data.list; // 获取用户角色关联信息
          } else {
            this.$message.err(res.message);
          }
        })
        .catch((err) => {
          console.log(err);
        });
      return promise;
    },
    migrateCancel() {
      this.$confirm("您确定取消移动吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.migrateVisible = false;
          this.migrate.orgCode = "";
          this.migrate.orgName = "";
          this.migrate.orgList1 = [];
          this.$nextTick(() => {
            this.$refs.org2tree.setCheckedKeys([]);
          });
        })
        .catch(() => { });
    },
    //  搜索
    search() {
      this.tableParams.form.pageNum = 1;
      this.getUser(this.tableParams.form);
      this.$refs.userTable.clearFilter();
    },
    // 遍历树
    getTreeAll(tree) {
      // 过滤接口中的数据变为tree所用数据
      let arr = [];
      if (!!tree && tree.length !== 0) {
        tree.forEach((item) => {
          let obj = {};
          obj = { ...item };
          obj.children = this.getTreeAll(item.children);
          arr.push(obj);
        });
      }
      return arr;
    },
    //  点击树事件
    nodeClick(item) {
      //  放入
      this.store.commit("system/sysPosts/treeItem", item);
      this.tableParams.form.pageNum = 1;
      this.tableParams.form.pageSize = 20;
      this.tableParams.form.orgCode = item.orgCode;
      this.tableParams.form.orgName = item.orgName;
      // let tree = this.store.state.system.organizManage.tree;
      // let checkedNodes = this.getTreeAll(tree).filter(function(x){
      //     return (x.orgCode === item.orgCode && x.orgName === item.orgCode);
      // });
      this.$refs.org1tree.setCheckedNodes([this.treeItem]);
      this.getUser(this.tableParams.form);
    },
    // 节点展开更新下拉板
    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")[1].style.left) + width + 15;
        if (allWid > document.body.clientWidth) {
          // console.log(width, num)
          this.$nextTick(() => {
            $(".el-select-dropdown")[1].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 - 15;
        let allWid =
          parseInt($(".el-select-dropdown")[1].style.left) + width + 15;
        if (document.body.clientWidth - allWid > 25) {
          // console.log(width, num)
          this.$nextTick(() => {
            $(".el-select-dropdown")[1].style.left = num + "px";
          });
        }
      }, 500);
    },
    //  计算树区域高度
    getTreeHeight(dom) {
      return window.innerHeight - dom.offsetTop;
    },
    //  计算table高度
    getTableHeight(dom) {
      return window.innerHeight - dom.offsetTop;
    },
    //  删除用户
    delUser(items) {
      let that = this;
      this.$confirm("确定要删除记录吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          console.log(items)
          this.store
            .dispatch("system/usersManage/delUser", items)
            .then((res) => {
              if (res.code === "0") {
                this.$message.success("删除成功");
                this.getUser(this.tableParams.form);
              } else {
                this.$message.error(res.message);
              }
            });
          // 删除用户下的角色关联
          that.axios
            .get(
              "pass/v1/sysuserroles/?userId=" +
              items[0].userId +
              "&pageNum=1&pageSize=100"
            )
            .then((result) => {
              if (result.data.list.length > 0) {
                for (let item of result.data.list) {
                  that.axios
                    .delete("pass/v1/sysuserroles/" + item.id)
                    .then((res) => {
                      // do somthing
                    })
                    .catch((err) => {
                      console.log(err);
                      return false;
                    });
                }
              }
            })
            .catch((err) => {
              console.log(err);
            });
        })
        .catch((err) => {
          console.log(err);
          this.$message.error("操作失败");
        });
    },
    //  操作
    operateClick(str, item) {
      this.operate = str;
      //
      switch (str) {
        case "add":
          this.userModal.show = true;
          this.table.item = item;
          break;
        case "edit":
          this.getUserInfo(item.id);
          break;
        case "detail":
          this.userModal.show = true;
          this.table.item = item;
          break;
        case "del":
          this.delUser([item]);
          break;
        case "post":
          this.postModal.show = true;
          this.table.item = item;
          //  查询岗位
          this.getPost(item.userId);
          break;
        case "czmm":
          this.resaltPassword(item);
          break;
        case "jcsd":
          this.unlock(item);
          break;
        case "tyqy":
          this.editUser(item);
          break;
        case "jh":
          this.activation(item);
          break;
      }
    },
    // 获取用户详情
    getUserInfo(userId) {
      this.axios
        .get("pass/v1/sysusers/" + userId)
        .then((res) => {
          if (res.code === "0") {
            this.userModal.show = true;
            this.table.item = res.data;
            this.activeRow = res.data;
          } else {
            this.$message.error(res.message);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 重置密码
    resaltPassword(item) {
      let password = "";
      switch (this.password) {
        case "0":
          if (item.userCode && item.userCode !== "" && item.userCode !== null) {
            password = item.userCode;
          } else {
            this.$message.error("当前用户账户名为空，重置失败");
          }
          break;
        case "1":
          if (item.cardNo && item.cardNo !== "" && item.cardNo !== null) {
            password = item.cardNo.substring(12);
          } else {
            this.$message.error("当前用户身份证信息为空，重置失败");
          }
          break;
        case "":
          this.$message.error("当前默认密码设置为空值，请管理员修改密码策略");
          break;
        default:
          password = this.password;
      }
      if (password !== "") {
        let data = {
          password: password,
        };
        this.axios
          .put("pass/v1/sysusers/resetPassword/" + item.userId, data)
          .then((res) => {
            if (res.code === "0") {
              this.$message.success(res.message);
              this.getUser(this.tableParams.form);
            } else {
              this.$message.error(res.message);
            }
          });
      }
    },
    // 解除锁定
    unlock(item) {
      this.axios
        .put("pass/v1/sysuserlogins/resetLoginInfo/" + item.userCode)
        .then((res) => {
          if (res.code === "0") {
            this.$message.success("已成功解锁用户");
            this.getUser(this.tableParams.form);
          } else {
            this.$message.error(res.message);
          }
        });
    },
    //  行点击
    userTableTrClick(item) {
      this.operateClick("detail", item);
    },
    //
    pageSizeChange(size) {
      this.tableParams.form.pageSize = size;
      this.getUser(this.tableParams.form);
    },
    //
    pageCurrentChange(index) {
      this.tableParams.form.pageNum = index;
      this.getUser(this.tableParams.form);
      // if (this.icoreFilterFlag) {
      //     this.icoreFilterFlag = false;
      // }
    },
    //  操作点击
    handleCommand(command) {
      this.operateClick(command[0], command[1]);
    },
    // //  table选中
    // selectChange (items) {
    //   this.table.items = items;
    // },
    //  弹窗完成
    userModalThen(str, item) {
      switch (str) {
        case "close":
          this.userModal.show = false;
          break;
        case "success":
          this.userModal.show = false;
          //  刷新
          // this.tableParams.form.userCode = item.userCode;
          // this.tableParams.form.userName = item.userName;
          // this.tableParams.form.mobile = item.mobile;
          // this.tableParams.form.orgCode = item.orgCode;
          // this.userStatus = '';
          this.getUser(this.tableParams.form);
          break;
      }
    },
    //  关闭弹窗
    userModalClose() { },
    // 更新主页机构职级
    updateOrgDutyLink() {
      this.$parent.getOrgDutyList();
    },
    //  选择下拉
    cascaderChange(codeArr) {
      //
      this.tableParams.form.orgCode = codeArr[codeArr.length - 1];
    },
    // ===================== 岗位 =============
    //  取岗位列表
    getPost(userId) {
      let form = JSON.parse(JSON.stringify(store.state.tableParams));
      this.table.loading = true;
      //  查询岗位列表
      form.pageSize = 100000;
      this.store.dispatch("system/sysPosts/list", form).then((res) => {
        this.table.loading = false;
        if (res.code === "0") {
          this.postModal.list = res.data.list;
          //  查询用户关联
          let form = JSON.parse(JSON.stringify(store.state.tableParams));
          form.userId = userId;
          form.pageSize = 100000;
          this.getPostUser(form);
        } else {
          this.$message.error(res.message);
        }
      });
    },
    //  取中间表
    getPostUser(form) {
      //  查询岗位列表
      form.pageSize = 100000;
      this.store.dispatch("system/usersManage/postUser", form).then((res) => {
        if (res.code === "0") {
          this.postModal.postUserList = res.data.list;
          //
          this.$nextTick(() => {
            this.defaultPostUser();
          });
        } else {
          this.$message.error(res.message);
        }
      });
    },
    //  选中默认已绑定项
    defaultPostUser() {
      //  选中
      let tab = this.postModal.list;
      let pul = this.postModal.postUserList;
      for (let item of tab) {
        for (let item2 of pul) {
          if (item.postId === item2.postId) {
            //  选中
            this.$refs["postTable"].toggleRowSelection(item, true);
            break;
          }
        }
      }
      //  重新选中默认项
      setTimeout(() => {
        this.postModal.items.forEach((item) => {
          for (let item2 of this.postModal.postUserList) {
            if (item.postId === item2.postId) {
              item.postType = item2.postType;
              break;
            }
          }
        });
        this.postModal.items = [...this.postModal.items];
      }, 100);
    },
    // 选择
    postSelectChange(items) {
      this.postModal.items = items;
      // //  清空
      // for (let item of this.postModal.list) {
      //   delete item.postType;
      // }
      //  设置岗位类型
      let selectItem = null;
      for (let item of items) {
        if (item.postType !== "1") {
          item.postType = "2";
        } else {
          selectItem = item;
        }
      }
      if (!selectItem && items.length > 0) {
        items[0].postType = "1";
      }
    },
    //  设为主岗位
    postTypeMain(item) {
      //  原主岗位设为 兼岗位
      this.postModal.items.forEach((item) => {
        item.postType = "2";
      });
      //
      item.postType = "1";
      this.postModal.items = [...this.postModal.items];
      // for (let item of this.postModal.list) {
      //   if (item.postType === '1') {
      //     item.postType = '2';
      //     break;
      //   }
      // }
      // //  设置主岗位
      // item.postType = '1';
      // console.log(this.postModal.list);
    },
    //  设置用户岗位
    async setInsertUserPosts(userId, items) {
      let form = {
        userId: userId,
        form: [],
      };
      //  整理数据  岗位类型：1-主岗位 2-兼岗位
      for (let item of items) {
        form.form.push({
          postId: item.postId,
          postType: item.postType,
        });
      }
      //
      const promise = await this.store
        .dispatch("system/userAuth/insertUserPosts", form)
        .then((res) => {
          if (res.code === "0") {
            this.$message.success("设置成功");
            this.postModal.show = false;
          } else {
            this.$message.error(res.message);
          }
        });
      return promise;
    },
    //  确定
    postUserOk() {
      //  格式化选中项
      //  提交
      this.setInsertUserPosts(this.table.item.userId, this.postModal.items);
    },
    //  格式化选中项
    filterPostUser() { },
    // 树形控件过滤数据
    filterOrgTree(value, data, node) {
      if (!value) return true;
      return data.orgName.indexOf(value) !== -1;
    },
    // 停用启用
    editUser(item) {
      let data = new FormData();
      let that = this;
      let status = item.status === "1" ? "0" : "1";
      data.append("status", status);
      data.append("leave", item.sysUserLogin.leave);
      that.store
        .dispatch("system/usersManage/editUser", {
          id: item.userId,
          form: data,
        })
        .then((res) => {
          if (res.code === "0") {
            let msg = res.data.status === "1" ? "启用" : "停用";
            that.$message.success("该账户已成功" + msg);
            res.data.orgName = item.orgName;
            that.updataUserInfo(res.data);
          } else {
            that.$message.error(res.message);
          }
        });
    },
    activation(item) {
      let data = new FormData();
      let that = this;
      data.append("loginStatus", "1");
      data.append("leave", "");
      that.store
        .dispatch("system/usersManage/editUser", {
          id: item.userId,
          form: data,
        })
        .then((res) => {
          if (res.code === "0") {
            that.$message.success("该账户已成功激活");
          } else {
            that.$message.error(res.message);
          }
        });
    },
    // 无刷新更新数据
    updataUserInfo(item) {
      let that = this;
      for (let i = 0; i < that.table.list.length; i++) {
        if (that.table.list[i].userId === item.userId) {
          for (let key in that.table.list[i]) {
            that.table.list[i][key] = item[key];
          }
        }
      }
    },
    // 查询机构名称
    getOrgName(list, code) {
      var name = "";
      for (let i = 0; i < list.length; i++) {
        try {
          if (list[i].orgCode === code) {
            name = list[i].orgName;
            return name;
          } else if (list[i].children && list[i].children.length >= 1) {
            name = this.getOrgName(list[i].children, code);
            if (name) {
              return name;
            }
          }
        } catch (error) {
          console.log(error);
        }
      }
      return name;
    },
    // 表格过滤
    // filterChange (filters) {
    //   var _this = this;
    //   _this.setFilterDatas(_this.$refs.userTable.columns, _this.$refs.userTable.tableData, ['userCode', 'userName','mobile','duty','orgName']);
    //   if(_this.filterStatus){
    //       _this.filterStatus = false;
    //       _this.initData();

    //   } else {
    //       _this.filterStatus = true;
    //       _this.tableParams.page.total = _this.$refs.userTable.tableData.length;
    //   }

    // },
    icoreFilterChange(item) {
      let filter1 = JSON.stringify(
        this.$refs["userTable"].store.states.filterIndividualMap
      ),
        filter2 = JSON.stringify(
          this.$refs["userTable"].store.states.filterMapper
        );
      if (filter1 === "{}" && filter2 === "{}") {
        this.tableParams.form.pageNum = this.setFilterCurrent;
        this.tableParams.page.total = this.tableParams.page.totalBack;
      } else {
        this.tableParams.form.pageNum = 1;
        this.tableParams.page.total = item.filterData.length;
      }
    },
    setCheckedKeys() {
      this.defaultExpand = false;
      for (var i = 0; i < this.$refs.orgTree.store._getAllNodes().length; i++) {
        this.$refs.orgTree.store._getAllNodes()[
          i
        ].expanded = this.defaultExpand;
      }
    },
    setCheckedNodes() {
      this.defaultExpand = true; // 展开所有节点
      for (var i = 0; i < this.$refs.orgTree.store._getAllNodes().length; i++) {
        this.$refs.orgTree.store._getAllNodes()[
          i
        ].expanded = this.defaultExpand;
      }
    },
    changeOrg() {
      this.$forceUpdate();
    },
    // 机构迁移树选择
    handleCheckChange(data, checked, node) {
      let res = this.$refs.org2tree.getCheckedNodes(false, true); //true，1. 是否只是叶子节点 2.选择的时候不包含父节点）
      if (res.length > 1) {
        // this.$message.warning('目标机构不可选择多个！');
        this.$refs.org2tree.setCheckedNodes([data]);
      } else if (res.length === 1) {
        this.migrate.orgCode = res[0].orgCode;
        this.migrate.orgName = res[0].orgName;
      } else if (res.length === 0) {
        this.migrate.orgCode = "";
        this.migrate.orgName = "";
      }
    },
    handleCheckChange1(data, checked, node) {
      let res = this.$refs.org1tree.getCheckedNodes(false, true);
      if (res.length > 1) {
        // this.$message.warning('查询机构不可选择多个！');
        this.$refs.org1tree.setCheckedNodes([data]);
      } else if (res.length === 1) {
        this.tableParams.form.orgCode = res[0].orgCode;
        this.tableParams.form.orgName = res[0].orgName;
      } else if (res.length === 0) {
        this.tableParams.form.orgCode = "";
        this.tableParams.form.orgName = "";
      }
    },
    // 批量添加
    beforeUpload(file) {
      const extension = file.name.substring(file.name.lastIndexOf('.') + 1)
      if (extension.indexOf('xls') == -1) {
        this.$alert('上传文件只能是 xls格式!', '系统提示', {
          confirmButtonText: '确定'
        })
        return false
      }
    },
    uploadSuccess(res, file, fileList) {
      console.log(res)
      if (res.code == '0') {
        // this.$message({
        //   message: '导入成功!',
        //   type: 'info'
        // })
        this.$alert('操作成功', '系统提示', {
          confirmButtonText: '确定'
        });
        this.pageCurrentChange(1)
      } else {
        this.$alert(res.message, '导入失败', {
          confirmButtonText: '确定'
        })
      }
      this.$refs.upload.clearFiles()
    }
  },
};
</script>
<style lang="less">
.userManage {
  padding: 15px;
  position: relative;
  min-width: 790px;
  .el-tree-node {
    .el-tree-node__label {
      border-bottom: 0;
    }
  }
}
.foot-style {
  margin: 5px 0 0;
  text-align: right;
}
.og-st-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  word-break: keep-all;
  padding-right: 60px;
}

.organizManage-main {
  height: 100%;
}

.public-function-div {
  font-size: 16px;
  padding: 10px 20px;
  border-bottom: 1px solid #d5d5d5;
  position: relative;
}

.organizManage-mainLeft {
  width: 30%;
  border-right: 1px solid #e0e0e0;
  float: left;
  overflow: hidden;
  height: inherit;
  ._refresh3 {
    padding: 10px 15px 9px 15px;
    border-bottom: 1px solid #d5d5d5;
    .el-dropdown {
      font-weight: bold;
      font-size: 14px;
      cursor: pointer;
    }
  }
}

.el-dropdown-menu {
  overflow-y: scroll;
  max-height: 200px;
}

.el-tree {
  overflow-x: hidden !important;
}

.organizManage-mainRight {
  width: 70%;
  float: left;
}

.FormorganizManage-main {
  margin: 20px 20px;
}
.post-m {
  margin: 20px;
}
.filterTree {
  width: 95%;
  margin: 10px 2.5%;
}
.el-select {
  width: 100%;
}
.individual-index {
  .setPosition {
    position: relative;
  }
}
.public-function-div .refresh {
  position: absolute;
  right: 15px;
  top: 10px;
}
.public-function-div .refresh2 {
  position: absolute;
  right: 80px;
  top: 10px;
}
.public-function-div .searchClass {
  width: 32px;
  height: 32px;
  font-size: 24px;
  line-height: 32px;
  text-align: center;
  color: #ccc;
  border: 1px solid #ccc;
  border-radius: 5px;
  position: absolute;
  right: 150px;
  top: 10px;
  cursor: pointer;
  background: white;
}
.color-primary {
  color: #409eff;
}
.el-dropdown {
  font-weight: bold;
  font-size: 14px;
  cursor: pointer;
}
</style>
