<template>
  <div class="box">
    <div>
      <div class="middlebox">
        <div class="contenttitle">
          权限管理 /
          <span class="contenttitleBold">用户管理</span>
        </div>
        <div class="seachinput">
          <el-select
            v-model="departments"
            placeholder="请选择账号"
            filterable
            :filter-method="remoteMethodes"
            default-first-option
            @change="quckDepartments"
            clearable
            size="small"
          >
            <el-option
              v-for="item in quckDepartment"
              :key="item.id"
              :label="item.surname"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </div>
      </div>
      <div>
        <div style="display: flex; margin-top: 7px">
          <div
            :style="
              'width: 208px;overflow: scroll;height:' +
              (window.pageHeight < 600 ? 480 : window.pageHeight - 100) +
              'px;background-color: #fff; border-radius: 8px'
            "
          >
            <div style="margin-top: 10px">
              <el-tree
                :data="treedata"
                :props="defaultProps"
                @node-click="handleNodeClick"
                highlight-current
                node-key="id"
                ref="itemType"
              >
                <span class="custom-tree-node" slot-scope="{ node, data }">
                  <div>
                    <span class="treeicons">
                      <!-- <i
                        class="el-icon-document-remove"
                        v-if="data.parentId == null"
                      ></i> -->
                      <img
                        style="width: 20px; height: 20px; vertical-align: sub"
                        src="@/assets/images/order.png"
                        v-if="!data.parentId"
                      />
                    </span>
                    <span :class="!data.parentId ? 'maxtitle' : 'mintitle'">{{
                      node.label
                    }}</span>
                  </div>
                </span>
              </el-tree>
            </div>
          </div>
          <div style="display: block">
            <div style="margin-left: 15px; display: flex">
              <div
                :style="
                  'width:' +
                  (window.pageWidth - 200 - 110 - 50 - 14) +
                  'px;padding: 15px;background-color: #fff;border-radius: 8px;'
                "
              >
                <el-table
                  :data="tableData"
                  row-key="id"
                  :height="
                    window.pageHeight < 600 ? 450 : window.pageHeight - 130
                  "
                  class="el-table__body-wrapper tbody"
                  highlight-current-row
                  @row-click="rowick"
                  ref="tableData"
                >
                  <el-table-column
                    type="index"
                    label="序号"
                    min-width="50"
                    align="center"
                  ></el-table-column>
                  <el-table-column prop="userName" label="账号" min-width="100">
                  </el-table-column>
                  <el-table-column prop="email" label="邮箱" min-width="150">
                  </el-table-column>
                  <!-- <el-table-column prop="email" label="所属角色" width=""> </el-table-column> -->
                  <el-table-column
                    prop="phoneNumber"
                    label="手机号"
                    min-width="130"
                  >
                  </el-table-column>
                  <el-table-column prop="surname" label="姓名" min-width="100">
                  </el-table-column>
                  <!-- <el-table-column label="操作" min-width="400">
                <template slot-scope="scope">
                  <el-button
                    type="primary"
                    @click="newlyincreased"
                    size="small">新增</el-button
                  >
                  <el-button type="primary" @click="editmony(scope.row)"
                  size="small">编辑</el-button
                  >
                  <el-button type="primary" @click="deleates(scope.row)"
                  size="small">删除</el-button
                  >
                  <el-button type="primary" @click="bandinuser(scope.row)"
                  size="small">绑定角色</el-button
                  >
                  <el-button type="primary" @click="editpassword(scope.row)"
                  size="small">修改密码</el-button
                  >
                  <el-button type="primary" @click="btnMenu(scope.row)"
                  size="small">菜单权限</el-button
                  >
                </template>
              </el-table-column> -->
                </el-table>
              </div>
              <!-- 按钮区域 -->
              <div style="margin-left: 10px">
                <el-button type="" @click="newlyincreased" class="commonbutton"
                  >新增</el-button
                >
                <div style="margin-top: 10px">
                  <el-button type="" @click="editmony" class="commonbutton"
                    >编辑</el-button
                  >
                </div>
                <div style="margin-top: 10px">
                  <el-button type="" @click="deleates" class="deleteButton"
                    >删除</el-button
                  >
                </div>
                <div style="margin-top: 10px">
                  <el-button type="" @click="bandinuser" class="commonbutton"
                    >绑定角色</el-button
                  >
                </div>
                <div style="margin-top: 10px">
                  <el-button type="" @click="editpassword" class="commonbutton"
                    >修改密码</el-button
                  >
                </div>
                <div style="margin-top: 10px">
                  <el-button type="" @click="btnMenu" class="commonbutton"
                    >菜单权限</el-button
                  >
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 编辑 -->
      <el-dialog
        :title="title == 1 ? '新增用户' : '修改用户'"
        :visible.sync="dialogVisible"
        width="700px"
        :close-on-click-modal="false"
      >
        <el-tabs
          v-model="activeName"
          v-if="title == 2 ? true : false"
          @tab-click="handleClick"
          style="height: 400px"
        >
          <el-tab-pane label="用户信息" name="first">
            <el-form
              v-if="dialogVisible"
              ref="form"
              :model="form"
              label-width="80px"
              :rules="ruless"
            >
              <el-row>
                <el-col :span="12">
                  <el-form-item label="姓名" prop="surname">
                    <el-input
                      v-model="form.surname"
                      size="small"
                    /> </el-form-item
                ></el-col>
                <el-col :span="12">
                  <el-form-item label="用户名" prop="userName">
                    <el-input
                      v-model="form.userName"
                      size="small"
                    /> </el-form-item
                ></el-col>

                <!-- <el-col :span="12">
                  <el-form-item label="名称" prop="name">
                    <el-input v-model="form.name"></el-input> </el-form-item
                ></el-col> -->
                <el-col :span="12">
                  <el-form-item label="手机号" prop="phoneNumber">
                    <el-input
                      v-model="form.phoneNumber"
                      size="small"
                    /> </el-form-item
                ></el-col>
                <el-col :span="12">
                  <el-form-item label="邮箱">
                    <el-input
                      v-model="form.email"
                      size="small"
                    ></el-input> </el-form-item
                ></el-col>
                <el-col :span="12">
                  <el-form-item label="科室">
                    <!--
                    <div style="margin-top: -30px">
                      当前选中的组织<span> {{ orgIds }}</span>
                    </div>
                    -->
                    <el-cascader
                      v-model="orgId"
                      :options="organizationalstructure"
                      ref="example"
                      popper-class="example"
                      @change="cascaderchang"
                      :props="{
                        expandTrigger: 'hover',
                        label: 'displayName',
                        children: 'treeChildren',
                        checkStrictly: true,
                        value: 'id',
                      }"
                      size="small"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="是否激活">
                    <el-checkbox
                      v-model="form.isActive"
                      true-label="true"
                      false-label="false"
                    ></el-checkbox>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="操作类别" prop="operatorType">
                    <el-select
                      v-model="form.operatorType"
                      placeholder="请选择操作类别"
                      size="small"
                    >
                      <el-option
                        v-for="item in operatorType"
                        :key="item.id"
                        :label="item.displayName"
                        :value="item.id"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="签名图片">
                    <el-upload
                      class="avatar-uploader"
                      :action="actionUrl"
                      :show-file-list="false"
                      :on-change="getFile"
                    >
                      <i class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                    <div v-if="form.userSign" style="display: inline-block;position: relative;">
                      <img
                        ref="phoUrl"
                        :src="form.userSign"
                        class="avatar"
                      />
                     <span class="el-upload-delete">
                      <i class="el-icon-circle-close" @click="handleRemove"></i>
                     </span>
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="用户图片">
                    <el-upload
                      class="avatar-uploader"
                      :action="actionUrl"
                      :show-file-list="false"
                      :on-change="getFiles"
                    >
                      <i class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                    <div v-if="form.userPhoto" style="display: inline-block;position: relative;">
                      <img ref="phoUrl" :src="form.userPhoto" class="avatar" />
                      <span class="el-upload-delete">
                      <i class="el-icon-circle-close" @click="handleRemoves"></i>
                     </span>
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="密码"
                    prop="password"
                    v-if="title == 1 ? true : false"
                  >
                    <el-input v-model="form.password"></el-input> </el-form-item
                ></el-col>
              </el-row>
            </el-form>
          </el-tab-pane>
          <!-- 选择角色 -->
          <el-tab-pane label="角色">
            <el-checkbox-group v-model="form.roleNames">
              <el-checkbox
                v-model="item.id"
                :label="item.name"
                v-for="(item, index) in checkList"
                :key="index"
                @change="handleCheckAllChange"
              >
              </el-checkbox>
            </el-checkbox-group>
          </el-tab-pane>
          <el-tab-pane label="科室操作权限">
            <div style="overflow-y: scroll; height: 350px">
              <el-tree
                :props="{
                  label: 'displayName',
                  children: 'treeChildren',
                }"
                :default-checked-keys="department"
                :default-expand-all="true"
                show-checkbox
                :data="setupdepartments"
                node-key="id"
                @check="iscrentddepartment"
                ref="department"
                size="small"
              />
            </div>
          </el-tab-pane>
          <el-tab-pane label="项目类别权限">
            <div style="overflow-y: scroll; height: 350px">
              <el-tree
                :props="{
                  label: 'displayName',
                  children: 'treeChildren',
                }"
                :default-checked-keys="haveitemtype"
                :default-expand-all="true"
                show-checkbox
                :data="itemtype"
                node-key="id"
                @check="iscrentditemtype"
                ref="haveitemtype"
                size="small"
              />
            </div>
          </el-tab-pane>
        </el-tabs>
        <!-- //新增 -->
        <el-form
          v-show="title == 1 ? true : false"
          v-if="dialogVisible"
          ref="form"
          :model="form"
          label-width="80px"
          :rules="rules"
        >
          <el-tabs style="height: 400px">
            <el-tab-pane label="用户信息">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="姓名" prop="surname">
                    <el-input
                      v-model="form.surname"
                      size="small"
                    ></el-input> </el-form-item
                ></el-col>
                <el-col :span="12">
                  <el-form-item label="用户名" prop="userName">
                    <el-input
                      v-model="form.userName"
                      size="small"
                    ></el-input> </el-form-item
                ></el-col>
                <!-- <el-col :span="12">
              <el-form-item label="名称" prop="userName">
                <el-input
                  v-model="form.usesurnamerName"
                ></el-input> </el-form-item
            ></el-col> -->
                <!-- <el-col :span="12">
                  <el-form-item label="名称" prop="name">
                    <el-input v-model="form.name"></el-input> </el-form-item
                ></el-col> -->
                <el-col :span="12">
                  <el-form-item label="手机号" prop="phoneNumber">
                    <el-input
                      v-model="form.phoneNumber"
                      size="small"
                    ></el-input> </el-form-item
                ></el-col>
                <el-col :span="12">
                  <el-form-item label="邮箱">
                    <el-input
                      v-model="form.email"
                      size="small"
                    ></el-input> </el-form-item
                ></el-col>
                <el-col :span="12">
                  <el-form-item
                    label="密码"
                    prop="password"
                    v-if="title == 1 ? true : false"
                  >
                    <el-input
                      show-password
                      v-model="form.password"
                      type="password"
                      autocomplete="new-password"
                      size="small"
                    ></el-input> </el-form-item
                ></el-col>
                <el-col :span="12">
                  <el-form-item label="是否激活">
                    <el-checkbox
                      v-model="form.isActive"
                      true-label="true"
                      false-label="false"
                    ></el-checkbox>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="操作类别" prop="operatorType">
                    <el-select
                      v-model="form.operatorType"
                      placeholder="请选择操作类别"
                      size="small"
                    >
                      <el-option
                        v-for="item in operatorType"
                        :key="item.id"
                        :label="item.displayName"
                        :value="item.id"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="签名图片">
                    <el-upload
                      class="avatar-uploader"
                      :action="actionUrl"
                      :show-file-list="false"
                      :on-change="getFile"
                    >
                      <i class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                    <div v-if="form.userSign" style="display: inline-block;position: relative;">
                      <img
                        ref="phoUrl"
                        :src="form.userSign"
                        class="avatar"
                      />
                     <span class="el-upload-delete">
                      <i class="el-icon-circle-close" @click="handleRemove"></i>
                     </span>
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="用户图片">
                    <el-upload
                      class="avatar-uploader"
                      :action="actionUrl"
                      :show-file-list="false"
                      :on-change="getFiles"
                    >
                      <i class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                    <div v-if="form.userPhoto" style="display: inline-block;position: relative;">
                      <img ref="phoUrl" :src="form.userPhoto" class="avatar" />
                      <span class="el-upload-delete">
                      <i class="el-icon-circle-close" @click="handleRemoves"></i>
                     </span>
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-tab-pane>
            <!-- 角色111 -->
            <el-tab-pane label="角色">
              <el-checkbox-group v-model="form.roleNames">
                <el-checkbox
                  v-model="item.id"
                  :label="item.name"
                  v-for="(item, index) in options"
                  :key="index"
                >
                </el-checkbox>
              </el-checkbox-group>
            </el-tab-pane>
            <!-- 组织11 -->
            <el-tab-pane label="所属科室">
              <el-cascader
                v-model="orgId"
                :options="organizationalstructure"
                ref="examples"
                popper-class="example"
                :show-all-levels="false"
                @change="cascaderchangs"
                :props="{
                  label: 'displayName',
                  children: 'treeChildren',
                  checkStrictly: true,
                  value: 'id',
                  expandTrigger: 'hover',
                }"
                size="small"
              ></el-cascader>
              <!-- <el-tree
                :data="newachitecture"
                show-checkbox
                :default-expand-all="true"
                @check="ischesc"
                node-key="id"
                ref="tree"
                :default-expanded-keys="nodekes"
                :default-checked-keys="[5]"
                :props="{ label: 'displayName', children: 'treeChildren' }"
              >
              </el-tree> -->
            </el-tab-pane>
            <el-tab-pane label="科室操作权限">
              <div style="overflow-y: scroll; height: 350px">
                <el-tree
                  :data="newdepartment"
                  show-checkbox
                  :default-expand-all="true"
                  @check="iscrentddepartments"
                  node-key="id"
                  ref="tree"
                  :props="{ label: 'displayName', children: 'treeChildren' }"
                  size="small"
                >
                </el-tree>
              </div>
            </el-tab-pane>
            <el-tab-pane label="项目类别权限">
              <div style="overflow-y: scroll; height: 350px">
                <el-tree
                  :data="newitemtype"
                  show-checkbox
                  :default-expand-all="true"
                  @check="iscrentditemtypes"
                  node-key="id"
                  ref="newitemtype"
                  :props="{ label: 'displayName', children: 'treeChildren' }"
                  size="small"
                >
                </el-tree>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancellation" class="difference">取 消</el-button>
          <el-button type="primary" @click="addlsit" class="commonbutton"
            >确 定</el-button
          >
        </span>
      </el-dialog>

      <!-- 绑定用户组织弹框 -->
      <el-dialog
        title="绑定组织"
        :visible.sync="bindingdialogVisible"
        width="30%"
        :close-on-click-modal="false"
      >
        <el-row>
          <el-col :span="8">当前组织:</el-col>
          <!-- <el-col :span="16" v-for="(item, index) in values" :key="index">{{
          item.displayName
          }}</el-col> -->
          <el-col :span="8" v-for="(item, index) in values" :key="index">{{
            item
          }}</el-col>
        </el-row>
        <el-cascader
          style="margin-top: 10px"
          v-model="values"
          :options="option"
          :props="{
            value: 'displayName',
            label: 'displayName',
            children: 'treeChildren',
            checkStrictly: true,
          }"
          @change="handleChange"
        ></el-cascader>
        <span slot="footer" class="dialog-footer">
          <el-button @click="bindingdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="binduser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 用户绑定管理弹框 -->
      <el-dialog
        title="绑定角色"
        :visible.sync="useerdialogVisible"
        width="30%"
        :close-on-click-modal="false"
      >
        <el-row>
          <el-col :span="8">所属角色:</el-col>
          <el-col :span="16" v-for="(item, index) in bingdusers" :key="index">{{
            item.name
          }}</el-col>
        </el-row>
        <el-select
          v-model="uservalue"
          multiple
          placeholder="请选择"
          style="margin-top: 15px"
          size="small"
        >
          <el-option
            v-for="item in useroptions"
            :key="item.id"
            :label="item.name"
            :value="item.name"
          >
          </el-option>
        </el-select>
        <span slot="footer" class="dialog-footer">
          <el-button @click="useerdialogVisible = false" class="difference"
            >取 消</el-button
          >
          <el-button type="primary" @click="Identifyusers" class="commonbutton"
            >确 定</el-button
          >
        </span>
      </el-dialog>
      <!-- 修改密码弹框 -->
      <el-dialog
        :title="`修改用户${usersName}密码`"
        :visible.sync="editpassworddialogVisible"
        width="30%"
        :close-on-click-modal="false"
      >
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="新密码">
            <el-input
              v-model="newPassWord"
              max="16"
              min="6"
              size="small"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="确认密码">
            <el-input
              v-model="confarmPassWord"
              max="16"
              min="6"
              size="small"
            ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button
            @click="editpassworddialogVisible = false"
            class="difference"
            >取 消</el-button
          >
          <el-button type="primary" @click="Changepassword" class="commonbutton"
            >确 定</el-button
          >
        </span>
      </el-dialog>

      <!--查看用户菜单权限-->
      <el-dialog
        title="查看用户菜单权限"
        :visible.sync="dialogWin.MenuPageSet"
        width="300px"
        :close-on-click-modal="false"
      >
        <MenuPageSet :params="dialogParams.MenuPageSet" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import {
  usreslist,
  newlists,
  delestsid,
  editmodify,
  getbook,
  userorganizat,
  organizationtree,
  userbind,
  usersroles,
  useraffiliation,
  reverseselection,
  usersinits,
  selectbinding,
  lognis,
} from "../../request/ruquset";
import { mapState } from "vuex";
import { isValid } from "@/utlis/validate";
import { getapi, postapi } from "@/api/api";
import { tcdate, deepCopy, objCopy } from "../../utlis/proFunc";
import MenuPageSet from "../../components/menuPage/MenuPageSet.vue";

// let validatePassword = (rule, value, callback) => {
//   var reg1 =
//     /^(?=.*\d)(?=.*[a-zA-Z])(?=.*[~!@#$%^&*.])[\da-zA-Z~!@#$%^&*.]{6,}$/; //密码必须是8位以上、必须含有字母、数字、特殊符号
//   var reg2 = /(123|234|345|456|567|678|789|012)/; //不能有3个连续数字
//   if (!reg1.test(value)) {
//     callback(new Error("密码必须是6位以上、必须含有字母、数字、特殊符号"));
//   } else if (reg2.test(value)) {
//     callback(new Error("不能有3个连续数字"));
//   } else {
//     callback();
//   }
// };
// let validatePassword = /^[a-zA-Z0-9@\$\^\.\*\\?]\{6,15}$/;
export default {
  components: {
    MenuPageSet,
  },
  data() {
    return {
      treedata: [],
      defaultProps: {
        children: "treeChildren",
        label: "displayName",
      },
      orgIds: "",
      orgId: "",
      confarmPassWord: "", //确认密码
      usersName: "", //用户名
      department: [], //选中的科室
      setupdepartments: [], //设置科室
      newPassWord: "", //新密码
      editpassworddialogVisible: false, //修改密码
      nodekes: [],
      activeName: "first",
      chaxunform: {
        surname: "",
        phoneNumber: "",
        userName: "",
      },
      useroptions: [],
      options: [],
      uservalue: [],
      useerdialogVisible: false,
      bindingdialogVisible: false,
      values: [],
      option: [],
      crdetcascader: [], //绑定组织显示

      dialogParams: {
        MenuPageSet: { opra: "role" }, //默认角色
      },

      //表单校验
      rules: {
        password: [
          {
            required: true,
            trigger: "blur",
            message: "密码不能为空",
          },
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
          // {
          //   required: true,
          //   trigger: "blur",
          //   validator: validatePassword,
          // },
        ],
        email: [
          {
            required: true,
            message: "请输入邮箱地址",
            trigger: "blur",
          },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        phoneNumber: [
          { required: true, message: "请输入手机号", trigger: "blur" },
        ],

        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        surname: [
          { required: true, message: "请输入用户名称", trigger: "change" },
        ],
        roleNames: [
          { required: true, message: "请选择所属用户", trigger: "change" },
        ],
        operatorType: [
          { required: true, message: "请选择操作类别", trigger: "change" },
        ],
        nam: [{ required: true, message: "请输入名", trigger: "change" }],
      },
      ruless: {
        password: [
          {
            required: true,
            trigger: "blur",
            message: "密码不能为空",
          },
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
        email: [
          {
            required: true,
            message: "请输入邮箱地址",
            trigger: "blur",
          },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        phoneNumber: [
          { required: true, message: "请输入手机号", trigger: "blur" },
        ],

        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        surname: [
          { required: true, message: "请输入用户名称", trigger: "change" },
        ],
        roleNames: [
          { required: true, message: "请选择所属用户", trigger: "change" },
        ],
        operatorType: [
          { required: true, message: "请选择操作类别", trigger: "change" },
        ],
        nam: [{ required: true, message: "请输入名", trigger: "change" }],
      },
      tableData: [],
      optionsArr: [],
      dialogVisible: false,
      modetype: "",
      total: 0,
      form: {
        surname: "",
        name: "",
        email: "",
        surname: "",
        phoneNumber: "",
        password: "",
        roleNames: [],
        userName: "",
        password: "",
        isActive: true,
        userSign: "",
        userPhoto: "",
        operatorType: "",
      },
      roleNames: [],
      are: [],
      checkList: [], //多选框
      pages: {
        SkipCount: 0,
        MaxResultCount: 1000,
      },
      title: 1,
      rowid: "",
      userid: "",
      bingdusers: [], //s所属用户角色
      organizationalstructure: [], //组织架构
      defaultKeys: [], //选中的
      newachitecture: [], //新增弹框获取组织数据
      // customer:[]
      password: "",
      passwordid: "",
      newdepartment: [], //新增科室
      curRow: {},
      itemtype: [],
      haveitemtype: [],
      newitemtype: [],
      departments: "",
      quckDepartment: [],
      initTableData: [],
      actionUrl: "",
      operatorType: [
        {
          id: "0",
          displayName: "操作员",
        },
        {
          id: "1",
          displayName: "医生",
        },
        {
          id: "2",
          displayName: "总检医生",
        },
        {
          id: "3",
          displayName: "医生和总检医生",
        },
      ],
    };
  },
  computed: {
    ...mapState(["window", "dialogWin", "dataTransOpts", "changepassword"]),
  },
  created() {
    this.password = this.changepassword;
    this.btnQuery();
    this.gettreedata();
    this.idkes = window.sessionStorage.getItem("dataidkes");
  },

  methods: {
    handleRemove(){
      this.form.userSign=this.$options.data().form.userSign
    },
    handleRemoves(){
      this.form.userPhoto=this.$options.data().form.userPhoto
    },
    quckDepartments(e) {
      if (e) {
        let currentKey = "";
        this.quckDepartment.forEach((item) => {
          if (e == item.id) {
            currentKey = item.organizationUnitId;
          }
        });
        this.$refs["itemType"].setCurrentKey(currentKey);
        let selected = this.$refs["itemType"].getCurrentNode();
        if (
          this.$refs["itemType"].getNode(selected) &&
          this.$refs["itemType"].getNode(selected).parent
        ) {
          this.expandParents(this.$refs["itemType"].getNode(selected).parent);
        }
        postapi(
          "/api/identity/users/getlistinorganizationunit",{
            organizationUnitId:currentKey
          }
        ).then((res) => {
          if (res.code != -1) {
            this.tableData = res.data;
            this.tableData.forEach((item, index) => {
              if (e == item.id) {
                this.$refs["tableData"].setCurrentRow(item);
                this.rowick(item);
                this.searchup(item, index);
              }
            });
          }
        });
      } else {
        this.remoteMethodes();
      }
    },
    remoteMethodes(keyWords) {
      if (keyWords) {
        this.quckDepartment = [];
        this.initTableData.forEach((item) => {
          if (
            item.userName.toLowerCase().indexOf(keyWords.toLowerCase()) > -1 ||
            item.simpleCode.toLowerCase().indexOf(keyWords.toLowerCase()) > -1
            || item.surname.toLowerCase().indexOf(keyWords.toLowerCase()) > -1
          ) {
            this.quckDepartment.push(item);
          }
        });
      } else {
        this.quckDepartment = deepCopy(this.initTableData);
      }
    },
    expandParents(node) {
      node.expanded = true;
      if (node.parent) {
        this.expandParents(node.parent);
      }
    },
    searchup(data, index) {
      this.$nextTick(() => {
        if (index == 0) {
          index = 1;
        }
        const targetTop = this.$refs["tableData"].$el
          .querySelectorAll(".el-table__body tr")
          [index - 1].getBoundingClientRect().top;
        const containerTop = this.$refs["tableData"].$el
          .querySelector(".el-table__body")
          .getBoundingClientRect().top;
        const scrollParent = this.$refs["tableData"].$el.querySelector(
          ".el-table__body-wrapper"
        );
        scrollParent.scrollTop = targetTop - containerTop;
      });
    },
    getFile(file, fileList) {
      //上传头像
      this.getBase64(file.raw).then((res) => {
        this.form.userSign = res;
        console.log(res);
      });
    },
    getFiles(file, fileList) {
      //上传头像
      this.getBase64(file.raw).then((res) => {
        this.form.userPhoto = res;
      });
    },
    getBase64(file) {
      //把图片转成base64编码
      return new Promise(function (resolve, reject) {
        let reader = new FileReader();
        let imgResult = "";
        reader.readAsDataURL(file);
        reader.onload = function () {
          imgResult = reader.result;
        };
        reader.onerror = function (error) {
          reject(error);
        };
        reader.onloadend = function () {
          resolve(imgResult);
        };
      });
    },
    cancellation() {
      this.dialogVisible = false;
      this.form = this.$options.data().form;
      this.roleNames = this.$options.data().roleNames;
      this.department = this.$options.data().department;
      this.orgId = this.$options.data().orgId;
      this.haveitemtype = this.$options.data().haveitemtype;
    },
    cascaderchang(v) {
      if (v.length > 1) {
        this.orgId = this.orgId.slice(-1)[0];
      } else {
        this.orgId = this.orgId[0];
      }
      this.$refs.example.toggleDropDownVisible();
    },
    cascaderchangs(v) {
      if (v.length > 1) {
        this.orgId = this.orgId.slice(-1)[0];
      } else {
        this.orgId = this.orgId[0];
      }
      this.$refs.examples.toggleDropDownVisible();
    },
    gettreedata() {
      getapi("/api/app/organization-units/by-code-all").then((res) => {
        if (res.code != -1) {
          this.treedata = res.data;
        }
      });
    },
    handleNodeClick(data) {
      this.department = data.displayName;
      postapi(
        "/api/identity/users/getlistinorganizationunit",{
          organizationUnitId:data.id
        }
      ).then((res) => {
        if (res.code != -1) {
          this.tableData = res.data;
        }
      });
    },
    rowick(row) {
      this.curRow = row;
      // posjrctid(row.id).then((res) => {
      //   this.curRow = { ...res.data };
      // });
    },
    iscrentddepartment() {
      this.department = this.$refs.department.getCheckedKeys(true);
    },
    iscrentddepartments() {
      this.department = this.$refs.tree.getCheckedKeys(true);
    },
    iscrentditemtype() {
      this.haveitemtype = this.$refs.haveitemtype.getCheckedKeys(true);
    },
    iscrentditemtypes() {
      this.haveitemtype = this.$refs.newitemtype.getCheckedKeys(true);
    },
    //修改密码确定按钮
    Changepassword() {
      if (this.newPassWord == "") {
        this.$message.warning("请输入新密码");
      } else if (this.confarmPassWord == "") {
        this.$message.warning("请输入确认密码");
      } else if (this.newPassWord != this.confarmPassWord) {
        this.$message.warning("二次输入密码不一致");
      } else {
        postapi("/api/identity/users/resetpassword", {
          userId: this.passwordid,
          newPassWord: this.newPassWord,
        }).then((res) => {
          if (res.code != -1) {
            this.editpassworddialogVisible = false;
            //this.$message.success("修改成功");
          }
        });
      }
    },
    //修改密码
    editpassword() {
      if (this.curRow.id == undefined) {
        this.$message.warning("请选择操作的数据");
      } else {
        this.editpassworddialogVisible = true;
        this.passwordid = this.curRow.id;
        this.usersName = this.curRow.surname;
      }
    },
    // 查看用户菜单权限
    btnMenu(row) {
      if (this.curRow.id == undefined) {
        this.$message.warning("请选择操作的数据");
      } else {
        this.dialogParams.MenuPageSet.opra = "user";
        this.dataTransOpts.tableS.adp_users.id = this.curRow.id;
        this.dialogWin.MenuPageSet = true;
        setTimeout(() => {
          this.dataTransOpts.refresh.role_menu_info.M++;
        }, 20);
      }
    },

    //新增选择的
    ischesc() {
      this.nodekes = this.$refs.tree.getCheckedKeys(true);
    },
    //选中的组织
    iscrentd() {
      this.defaultKeys = this.$refs.trees.getCheckedKeys(true);
      //  console.log("222", this.$refs.tree.defaultKeys(true));
    },
    //选中适合的值
    handleCheckAllChange() {
      // this.form.roleNames = this.roleNames;
      // console.log(this.activeName);
    },
    //table页切换
    handleClick() {
      if (this.activeName == "1") {
        //获取当前绑定用户
        useraffiliation(this.form.id).then((res) => {
          if (res.code != -1) {
            if (res.data.items && res.data.items.length > 0) {
              let val = res.data.items.map((item) => {
                return item.name;
              });
              this.$set(this.form, "roleNames", val);
            } else {
              this.$set(this.form, "roleNames", []);
            }
          }
        });
      }
    },

    //用户列表查询
    // inquireabout() {
    //   this.btnQuery();
    //   //  usreslist()
    // },
    btnQuery() {
      postapi("/api/identity/users/getlistinorganizationunit").then((res) => {
        if (res.code != -1) {
          this.tableData = res.data;
          this.quckDepartment = [...res.data];
          this.initTableData = [...res.data];
        }
      });
    },

    onchang(v) {
      // this.form.roleNames[0] = v;
    },
    //级联选择器
    handleChange(value) {
      this.values = value;
    },

    // getlist() {
    //   usreslist(this.pages).then((res) => {
    //     this.tableData = res.data.items;

    //     this.total = res.data.totalCount;
    //     console.log(res);
    //   });
    // },

    //绑定
    binding(row) {
      this.bindingdialogVisible = true;
      this.rowid = row.id;
      organizationtree().then((res) => {
        if (res.code != -1) {
          this.option = res.data;
        }
      });

      // reverseselection(row.id).then((res) => {
      //   this.crdetcascader = res.data;
      //   console.log(res);
      // });
      // userorganizat(row.id, this.idkes ).then((res) => {
      //   console.log(res);
      // });
    },
    //绑定用户角色
    bandinuser() {
      if (this.curRow.id == undefined) {
        this.$message.warning("请选择操作的数据");
      } else {
        this.useerdialogVisible = true;
        this.userid = this.curRow.id;
        usersroles().then((res) => {
          if (res.code != -1) {
            this.useroptions = res.data.items;
          }
        });
        useraffiliation(this.curRow.id).then((res) => {
          if (res.code != -1) {
            res.data.items.forEach((element) => {
              this.uservalue = element[name];
            });
            // this.uservalue=res.data.items[name]
            this.bingdusers = res.data.items;
          }

          // console.log(res);
        });
        // this.form.roleNames.push(row.userName)
        // userbind(row.id,{roleNames:this.form.roleNames}).then(res=>{
        //   console.log(res)
        // })
        // console.log(row);
      }
    },
    //确定绑定
    Identifyusers() {
      // let are = [];
      // console.log(this.uservalue);
      // are.push(this.uservalue);
      // this.uservalue = are;
      if (this.uservalue !== "") {
        userbind(this.userid, { roleNames: this.uservalue }).then((res) => {
          if (res.code != -1) {
            this.btnQuery();
            this.useerdialogVisible = false;
            //this.$message.success("绑定成功");
          }
        });
      } else {
        this.$message.warning("请选择用户");
      }
    },
    //绑定
    binduser() {
      if (this.values.length == 0) {
        this.$message.warning("请选中");
      } else {
        userorganizat(this.rowid, this.idkes).then((res) => {
          if (res.code != -1) {
            this.bindingdialogVisible = false;
            this.btnQuery();
            //this.$message.success("操作成功");
          }
          // this.values = [];
          // console.log(res);
        });
      }
    },
    //新增用户
    newlyincreased() {
      this.dialogVisible = true;
      this.title = 1;
      if (this.title == 1) {
        this.form = this.$options.data().form;
        this.orgId = this.department;
      }
      getbook().then((res) => {
        //  res.data.items.forEach((element) => {
        //     this.form.roleNames = element.name;
        //     console.log(element);
        //   });
        if (res.code != -1) {
          this.options = res.data.items;
        }
      });

      organizationtree().then((res) => {
        if (res.code != -1) {
          this.newachitecture = res.data;
          this.newdepartment = res.data;
          this.organizationalstructure = res.data;
          tcdate(this.organizationalstructure);
        }
      });
      getapi("/api/app/item-type/by-code-all").then((res) => {
        if (res.code != -1) {
          this.newitemtype = [...res.data];
        }
      });
    },
    //确定添加或修改
    addlsit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.title == 1) {
            let arrs = [];

            // arrs.push(this.roleNames);
            // console.log(arrs)
            let obj = {
              userName: this.form.userName,
              name: this.form.name,
              surname: this.form.surname,
              email: this.form.email,
              usesurnamerName: this.form.usesurnamerName,
              phoneNumber: this.form.phoneNumber,
              password: this.form.password,
              roleNames: this.form.roleNames,
              isActive: this.form.isActive,
              email: this.form.email,
              operatorType: this.form.operatorType,
              userSign: this.form.userSign,
              userPhoto: this.form.userPhoto,
            };
            if (this.form.roleNames.length == 0) {
              this.$message.warning("请选择角色");
            } else if (this.orgId == "" || this.orgId == null) {
              this.$message.warning("请选择科室");
            } else {
              newlists(obj).then((res) => {
                if (res.code != -1) {
                  this.form = res.data;
                  postapi(
                    `/api/app/abpuserdepartment/createmany?UserId=${this.form.id}`,
                    this.department
                  ).then((res) => {
                    if (res.code != -1) {
                      postapi(
                        "/api/app/organization-units/user-organization-unit",
                        { userId: this.form.id, orgId: this.orgId }
                      ).then((res) => {
                        if (res.code != -1) {
                          postapi(
                            `/api/app/UserItemType/CreateMany?UserId=${this.form.id}`,
                            this.haveitemtype
                          ).then((res) => {
                            if (res.code != -1) {
                              this.dialogVisible = false;
                              //this.$message.success("新增成功");
                              this.form = this.$options.data().form;
                              this.roleNames = this.$options.data().roleNames;
                              this.department = this.$options.data().department;
                              this.curRow = this.$options.data().curRow;
                              this.orgId = this.$options.data().orgId;
                              this.haveitemtype =
                                this.$options.data().haveitemtype;
                              this.$refs["tableData"].setCurrentRow("");
                              this.btnQuery();
                            }
                          });
                        }
                      });
                    }
                  });
                }
              });
            }
          } else if (this.title == 2) {
            // this.roleNames=arrs
            let obj = {
              userName: this.form.userName,
              name: this.form.name,
              surname: this.form.surname,
              email: this.form.email,
              usesurnamerName: this.form.usesurnamerName,
              phoneNumber: this.form.phoneNumber,
              password: this.form.password,
              roleNames: this.form.roleNames,
              isActive: this.form.isActive,
              email: this.form.email,
              operatorType: this.form.operatorType,
              userSign: this.form.userSign,
              userPhoto: this.form.userPhoto,
              // roleNames: this.form.roleNames,
            };
            if (this.orgId == "" || this.orgId == null) {
              return this.$message.warning("请选择科室");
            }
            console.log(this.form.roleNames);
            if (this.form.roleNames.length == 0) {
              this.$message.warning("请选则用户角色");
              return;
            }

            let msg = "";
            //更新用户与所属角色
            postapi(`/api/identity/users/update?id=${this.form.id}`, obj).then(
              (res) => {
                if (res.code != -1) {
                  //更新科室权限
                  postapi(
                    `/api/app/abpuserdepartment/createmany?UserId=${this.form.id}`,
                    this.department
                  ).then((res) => {
                    if (res.code != -1) {
                      postapi(
                        "/api/app/organization-units/user-organization-unit",
                        { userId: this.form.id, orgId: this.orgId }
                      ).then((res) => {
                        if (res.code != -1) {
                          postapi(
                            `/api/app/UserItemType/CreateMany?UserId=${this.form.id}`,
                            this.haveitemtype
                          ).then((res) => {
                            if (res.code != -1) {
                              this.dialogVisible = false;
                              this.form = this.$options.data().form;
                              this.roleNames = this.$options.data().roleNames;
                              this.department = this.$options.data().department;
                              this.curRow = this.$options.data().curRow;
                              this.orgId = this.$options.data().orgId;
                              this.haveitemtype =
                                this.$options.data().haveitemtype;
                              this.$refs["tableData"].setCurrentRow("");
                              //this.$message.success("操作成功！");
                              this.btnQuery();
                            }
                          });
                        }
                      });
                    }
                  });
                }
              }
            );
          }
        }
      });
    },
    //删除方法
    deleates() {
      if (this.curRow.id == undefined) {
        this.$message.warning("请选择删除的数据");
      } else {
        let id = this.curRow.id.id;
        // delestsid(id).then((res) => {
        //   console.log(res);
        //   this.btnQuery();
        //   console.log("删除成功");
        // });
        this.$confirm("是否确定删除, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          cancelButtonClass: "difference",
          confirmButtonClass: "commonbutton",
        })
          .then(() => {
            postapi(`/api/identity/users/delete?id=${this.curRow.id}`).then(
              (res) => {
                if (res.code != -1) {
                  this.btnQuery();
                  this.curRow = this.$options.data().curRow;
                  //this.$message.success("删除成功");
                }
              }
            );
          })
          .catch(() => {});
      }
    },

    //编辑修改
    editmony() {
      if (this.curRow.id == undefined) {
        this.$message.warning("请选择操作的数据");
      } else {
        this.dialogVisible = true;
        this.title = 2;
        // this.form.roleNames = this.roleNames;
        if (this.title == 2) {
          // row里面没有roleNames字段
          //const form = JSON.parse(JSON.stringify(row));
          getapi("/api/identity/users/getinfo", {
            id: this.curRow.id,
          }).then((res) => {
            if (res.code != -1) {
              const form = deepCopy(res.data);
              this.form = {
                ...form,
                roleNames: [],
              };
              this.form.roleNames = [];
            }
          });
          //获取组织架构
          organizationtree().then((res) => {
            if (res.code != -1) {
              this.organizationalstructure = res.data;
              tcdate(this.organizationalstructure);
              this.setupdepartments = res.data;
            }
          });
          // postapi(`/api/app/abpuserdepartment/createmany?UserId=${this.form.id}`,{orgId:this.orgId[0]}).then(res=>{
          //   console.log(res,'wwwwwwwwwwwww');
          // })
          useraffiliation(this.curRow.id).then((res) => {
            if (res.code != -1) {
              if (res.data.items && res.data.items.length > 0) {
                let val = res.data.items.map((item) => {
                  return item.name;
                });
                this.$set(this.form, "roleNames", val);
              } else {
                this.$set(this.form, "roleNames", []);
              }
            }
          });

          //根据用户ID查组织信息
          getapi(
            `/api/app/organization-units/organization-unit-by-user-id/${this.curRow.id}`
          ).then((res) => {
            if (res.code != -1 && res.data.length > 0) {
              this.orgId = res.data[0].id;
            }
          });

          //获取科室权限 编辑
          getapi(
            `/api/app/abpuserdepartment/getuserdepartment?UserId=${this.curRow.id}`
          ).then((res) => {
            // default-checked-keys
            if (res.code != -1) {
              this.department = res.data;
            }
          });
        }

        // useraffiliation(row.id).then((res) => {
        //   this.form.roleNames = res.data.items[0].name;
        //   // res.data.items.forEach(item=>{
        //   //   this.form.roleNames=item.name
        //   //   console.log(item)
        //   // })
        //   console.log("form", this.form);
        //   // console.log(res);
        //   console.log(res, "=====10010");
        //   this.$forceUpdate();
        // });
        getbook().then((res) => {
          const { code, data } = res;
          if (code != -1) {
            let options = data.items;
            this.checkList = options;
            // console.log(this.checkList, "checkList");
            this.options = options;
            // this.options = options.map((item, index) => {
            //   return {
            //     id: item.name,
            //     name: item.name,
            //   };
            // });
          }
        });
        getapi("/api/app/item-type/by-code-all").then((res) => {
          if (res.code != -1) {
            this.itemtype = [...res.data];
          }
        });
        postapi(
          `/api/app/UserItemType/GetUserItemType?UserId=${this.curRow.id}`
        ).then((res) => {
          if (res.code != -1) {
            this.haveitemtype = [...res.data];
          }
        });
      }
    },
    //分页
    handleSizeChange(v) {
      this.pages.MaxResultCount = v;
      this.btnQuery();
    },
    handleCurrentChange(v) {
      this.pages.SkipCount = v;
      this.btnQuery();
    },
  },
};
</script>
<style scoped>
@import "../../assets/css/global_button.css";
@import "../../assets/css/global_dialog.css";
@import "../../assets/css/global_table.css";
@import "../../assets/css/global_form.css";
@import "../../assets/css/global_input.css";
@import "../../assets/css/global.css";
.box {
  display: flex;
  flex-direction: column;
}
.layeredleftright {
  width: 100%;
  display: flex;
  flex-direction: column;
}
:deep .el-form-item {
  margin-bottom: 14px;
}
/* el-dialog的头部样式 */
:deep .el-dialog__header {
  padding: 11px 20px 11px;
}
/* el-dialog的主体样式 */
:deep .el-dialog__body {
  padding: 0px 20px 0px;
}
/* el-divider样式 */
:deep .el-divider--horizontal {
  margin: 0px 0 12px;
}
/* el-dialog的底部样式 */
:deep .el-dialog__footer {
  padding: 0px 20px 14px;
}
:deep .el-table tr {
  height: 33px;
}
:deep .el-tree-node > .el-tree-node__children {
  overflow: visible;
}
.seachinput {
  width: 250px;
  margin-right: 110px;
}
:deep .seachinput .el-select {
  width: 100%;
}
:deep.avatar-uploader{
  display: inline-block;
}
:deep.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
:deep.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
:deep.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
}
.avatar {
  width: 80px;
  height: 80px;
  display: block;
}
.el-upload-delete{
      position: absolute;
    top: 0;
    right: 0;
    line-height: 0;
    font-size: 18px;

}
</style>