<template>
  <div>
    <el-card class="elcard">
      <div slot="header">
        <span>用户管理</span>
      </div>
      <div>
        <div style="display: flex;padding: 0px 0px 2px;">
          
            <el-input v-model="pages.Filter" clearable  @change="btnQuery" placeholder="输入查询关键字" style="width: 200px" size="small" />
            <el-button style="margin-left: 5px;" type="primary" @click="btnQuery" size="small">查询</el-button>
        </div>
        
        <div style="display: flex">
          <div :style="'overflow: scroll;border: 1px solid;width:200px;height:' +(window.pageHeight < 600 ? 430 : window.pageHeight - 170) + 'px;'">
            <el-tree
              :data="treedata"
              :props="defaultProps"
              @node-click="handleNodeClick"
              highlight-current
            ></el-tree>
          </div>
          <div :style="'margin-left: 5px;width: '+(window.pageWidth - 200 - 50)+'px;'">
            <el-table highlight-current-row
              :height="window.pageHeight < 600 ? 430 : window.pageHeight - 170"              
              :data="tableData" size="small" border>
              <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 prop="name" label="名称" width=""> </el-table-column> -->
              <!-- <el-table-column prop="lastModificationTime" label="开始时间">
            <template slot-scope="scope">
              {{ scope.row.creationTime | dateFormat }}
            </template>
          </el-table-column>
          <el-table-column prop="lastModificationTime" label="结束时间">
            <template slot-scope="scope">
              {{ scope.row.lastModificationTime | dateFormat }}
            </template>
          </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="binding(scope.row)"
                >绑定组织</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
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>

      <!-- <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[2, 10, 20, 30]"
        :page-size="5"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total - 1"
      >
      </el-pagination> -->
      <!-- 编辑 -->
      <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="rules"
            >
              <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="科室">
                    <!--
                    <div style="margin-top: -30px">
                      当前选中的组织<span> {{ orgIds }}</span>
                    </div>
                    -->
                    <el-cascader
                      v-model="orgId"
                      :options="organizationalstructure"
                      :show-all-levels="false"
                      @change="cascaderchang"
                      :props="{
                        expandTrigger: 'hover',
                        label: 'displayName',
                        children: 'treeChildren',
                        checkStrictly: true,
                        value: 'id',
                      }" size="small" style="width:260px;" />
                  </el-form-item>
                </el-col>
                <!-- <el-col :span="12">
                  <el-form-item label="邮箱" >
                    <el-input v-model="form.email"></el-input> </el-form-item
                ></el-col> -->
                <el-col>
                  <el-form-item label="是否激活">
                    <el-checkbox v-model="form.isActive"></el-checkbox>
                  </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-col :span="12">
                  <el-form-item label="所属角色" prop="roleNames">
                    <el-select
                      v-model="form.roleNames"
                      placeholder="请选择"
                      @change="onchang"
                    >
                      <el-option
                        v-for="item in options"
                        :key="item.id"
                        :label="item.name"
                        :value="item.name"
                      >
                      </el-option>
                    </el-select>
                  </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="组织架构"> -->
          <!-- :default-checked-keys="defaultKeys" -->
          <!-- <el-tree
              :props="{
                label: 'displayName',
                children: 'treeChildren',
              }"
              :default-checked-keys="defaultKeys"
              :default-expand-all="true"
              show-checkbox
              :data="organizationalstructure"
              node-key="id"
              @check="iscrentd"
              ref="trees"
            >
            </el-tree> -->
          <!-- <div>
              当前选中的组织<span> {{ orgIds }}</span>
            </div>
            <el-cascader
              v-model="orgId"
              :options="organizationalstructure"
              :show-all-levels="false"
              @change="cascaderchang"
              :props="{
                label: 'displayName',
                children: 'treeChildren',
                checkStrictly: true,
                value: 'id',
              }"
            ></el-cascader> -->
          <!-- </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-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"></el-input> </el-form-item
                ></el-col>
                <el-col :span="12">
                  <el-form-item label="用户名" prop="userName">
                    <el-input v-model="form.userName"></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"
                    ></el-input> </el-form-item
                ></el-col>
                <!-- <el-col :span="12">
                  <el-form-item label="邮箱" >
                    <el-input v-model="form.email"></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"
                    ></el-input> </el-form-item
                ></el-col>

                <!-- <el-col :span="12">
                  <el-form-item label="所属角色" prop="roleNames">
                    <el-select
                      v-model="form.roleNames"
                      placeholder="请选择"
                      @change="onchang"
                    >
                      <el-option
                        v-for="item in options"
                        :key="item.id"
                        :label="item.name"
                        :value="item.name"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col> -->
                <el-col :span="12">
                  <el-form-item label="是否激活">
                    <el-checkbox
                      v-model="form.isActive"
                      :checked="true"
                    ></el-checkbox>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-tab-pane>
            <!-- 角色111 -->
            <el-tab-pane label="角色">
              <el-checkbox-group v-model="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
                :options="organizationalstructure"
                :show-all-levels="false"
                :props="{
                  label: 'displayName',
                  children: 'treeChildren',
                  checkStrictly: true,
                  value: 'id',
                }"
              ></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="ischesc"
                  node-key="id"
                  ref="tree"
                  :default-expanded-keys="nodekes"
                  :default-checked-keys="[5]"
                  :props="{ label: 'displayName', children: 'treeChildren' }"
                >
                </el-tree>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addlsit" class="bulletcommit"
            >确 定</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"
        >
          <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">取 消</el-button>
          <el-button type="primary" @click="Identifyusers" class="bulletcommit"
            >确 定</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"></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"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editpassworddialogVisible = false"
            >取 消</el-button
          >
          <el-button type="primary" @click="Changepassword" class="bulletcommit"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </el-card>
  </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";

// 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 {
  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: [], //绑定组织显示

      //表单校验
      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" },
        ],
        nam: [{ required: true, message: "请输入名", trigger: "change" }],
      },
      tableData: [],
      optionsArr: [],
      dialogVisible: false,
      modetype: "",
      total: 0,
      form: {
        surname: "fas",
        name: "ww",
        email: "45148415@qq.com",
        surname: "",
        phoneNumber: "",
        password: "1q2w3E*",
        roleNames: [],
        userName: "",
        password: "1q2w3E*",
        isActive: true,
      },
      roleNames: [],
      are: [],
      checkList: [], //多选框
      pages: {
        SkipCount: 0,
        MaxResultCount: 1000,
        Filter: "",
        // Filter:{
        //   userName:this.form.userName,
        //   phoneNumber:this.form.phoneNumber,
        //    surname: this.form.surname,

        // }
      },
      title: 1,
      rowid: "",
      userid: "",
      bingdusers: [], //s所属用户角色
      organizationalstructure: [], //组织架构
      defaultKeys: [], //选中的
      newachitecture: [], //新增弹框获取组织数据
      // customer:[]
      password: "",
      passwordid: "",
      newdepartment: [], //新增科室
    };
  },
  computed: {
    ...mapState(["window","changepassword"]),
  },
  created() {
    this.password = this.changepassword;
    console.log(this.password);
    this.btnQuery();
    this.gettreedata();
    this.idkes = localStorage.getItem("dataidkes");
  },

  methods: {
    cascaderchang(v) {
      console.log(v);
    },
    gettreedata() {
      getapi("/api/app/organization-units/by-code-all").then((res) => {
        this.treedata = res.data;
        console.log(res);
      });
    },
    handleNodeClick(data) {
      this.department = data.displayName;
      console.log(this.department);
      getapi(
        `/api/identity/users/getlistinorganizationunit?OrganizationUnitId=${data.id}`
      ).then((res) => {
        console.log(res);
        this.tableData = res.data;
      });
    },

    iscrentddepartment() {
      this.department = this.$refs.department.getCheckedKeys(true);
      console.log(this.department, "wwww");
    },
    //修改密码确定按钮
    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) => {
          this.$message.success("修改成功");
          this.editpassworddialogVisible = false;
        });
      }
      console.log(this.newPassWord);
    },
    //修改密码
    editpassword(row) {
      this.editpassworddialogVisible = true;
      this.passwordid = row.id;
      this.usersName = row.userName;
    },
    //新增选择的
    ischesc() {
      console.log("333", this.$refs.tree.getCheckedKeys(true));
      this.nodekes = this.$refs.tree.getCheckedKeys(true);
    },
    //选中的组织
    iscrentd() {
      console.log("222", this.$refs.trees.getCheckedKeys(true));
      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);
      console.log(this.form.roleNames);
    },
    //table页切换
    handleClick() {
      console.log(this.activeName);
      if (this.activeName == "1") {
        //获取当前绑定用户
        useraffiliation(this.form.id).then((res) => {
          console.log(res.data.items);
          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.getlist();
    //   //  usreslist()
    // },
    btnQuery(){
      getapi(`/api/identity/users/getlist?Filter=${this.pages.Filter}&MaxResultCount=${this.pages.MaxResultCount}`).then(res =>{
        if(res.code != -1){
          this.tableData = res.data.items
        }
      })
    },

    onchang(v) {
      // this.form.roleNames[0] = v;
      console.log(v);
    },
    //级联选择器
    handleChange(value) {
      this.values = value;
      console.log(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;
      console.log(row);
      this.rowid = row.id;
      organizationtree().then((res) => {
        this.option = res.data;
        console.log(this.option);
      });

      // reverseselection(row.id).then((res) => {
      //   this.crdetcascader = res.data;
      //   console.log(res);
      // });
      // userorganizat(row.id, this.idkes ).then((res) => {
      //   console.log(res);
      // });
    },
    //绑定用户角色
    bandinuser(row) {
      this.useerdialogVisible = true;
      this.userid = row.id;
      usersroles().then((res) => {
        this.useroptions = res.data.items;
        console.log(res);
      });
      useraffiliation(row.id).then((res) => {
        res.data.items.forEach((element) => {
          console.log(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) => {
          this.$message.success("绑定成功");
          this.getlist();
          this.useerdialogVisible = false;
        });
      } else {
        this.$message.success("请选择用户");
      }
    },
    //绑定
    binduser() {
      console.log(this.values);
      console.log(this.rowid);
      console.log(this.idkes);
      if (this.values.length == 0) {
        this.$message.success("请选中");
      } else {
        userorganizat(this.rowid, this.idkes).then((res) => {
          this.bindingdialogVisible = false;
          this.getlist();
          this.$message.success("操作成功");
          // this.values = [];
          // console.log(res);
        });
      }
    },
    //新增用户
    newlyincreased() {
      this.dialogVisible = true;
      this.title = 1;
      if (this.title == 1) {
        this.form = {};
        this.orgId = this.department;
        console.log(this.orgId);
        console.log(this.department, "1111111111111");
      }
      getbook().then((res) => {
        //  res.data.items.forEach((element) => {
        //     this.form.roleNames = element.name;
        //     console.log(element);
        //   });
        this.options = res.data.items;

        console.log(res, "====>>>>>res");
      });

      organizationtree().then((res) => {
        this.newachitecture = res.data;
        this.newdepartment = res.data;
        this.organizationalstructure = res.data;
        tcdate(this.organizationalstructure) 
        console.log(res, "1w");
      });
      console.log(this.title);
    },
    //确定添加或修改
    addlsit() {
      console.log(this.roleNames);
      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.roleNames,
              isActive: true,
            };
            if (this.roleNames.length == 0) {
              this.$message.success("请选择角色");
            } else {
              newlists(obj).then((res) => {
                if (res.code == 1) {
                  this.dialogVisible = false;
                  this.$message.success("新增成功");
                  // selectbinding({orgId:this.nodekes}).then(r=>{
                  //   this.$message.success('绑定成功')
                  // })
                }
                this.roleNames = [];
                this.getlist();
                console.log(res);
              });
            }
          } else if (this.title == 2) {
            console.log(this.orgId);

            // 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: true,
              // roleNames: 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){  //更新科室权限
                return postapi(`/api/app/abpuserdepartment/createmany?UserId=${this.form.id}`,this.department)
              }else{
                msg = res.message
              }   
            }).then( res=>{
              if(res.code != -1 && this.orgId.length > 0){
                return postapi('/api/app/organization-units/user-organization-unit',{ userId: this.form.id, orgId: this.orgId[this.orgId.length - 1]})
              }else{
                msg = res.message
              }            
            })
            
            if(msg){
              this.$message.error(msg);
            }else{
              this.$message.success("操作成功！");
              this.dialogVisible = false;
            }

            //
            //   console.log(this.form.roleNames);
            //   // let tempArr=[]              
            //   editmodify(this.form.id, obj).then((res) => {
            //     if (res.code == 1) {
            //       this.$message.success("修改成功");
            //       this.dialogVisible = false;
            //       this.getlist();
            //     }
            //     console.log(res);
            //     if (res.code == 1) {
            //       selectbinding({
            //         userId: this.form.id,
            //         orgId: this.orgId[0],
            //       }).then((res) => {
            //         console.log(res);
                    
            //         //api/app/organization-units/user-organization-unit
            //         postapi(
            //           `/api/app/abpuserdepartment/createmany?UserId=${this.form.id}`,
            //           this.orgId
            //         ).then((res) => {
            //           console.log(this.orgId);
            //           // this.$message.success("操作成功");
            //         });
            //         // this.$message.success("修改绑定组织成功");
            //       });
            //       // postapi(
            //       //   `/api/app/abpuserdepartment/createmany?UserId=${this.form.id}`,
            //       //   this.department
            //       // ).then((res) => {
            //       //   // this.$message.success("操作成功");
            //       // });
            //       console.log("aaaaaa");
            //     }
            //   });
            // } else {
            //   this.$message.success("请选则用户");
            // }
          }
        }
      });
    },
    //删除方法
    deleates(row) {
      let id = row.id;
      // delestsid(id).then((res) => {
      //   console.log(res);
      //   this.getlist();
      //   this.$message.success("删除成功");
      // });
      this.$confirm("是否确定删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          postapi(`/api/identity/users/delete?id=${row.id}`).then((res) => {
            this.getlist();
            this.$message.success("删除成功");
          });
        })
        .catch(() => {});

      console.log(row);
    },

    //编辑修改
    editmony(row) {
      console.log(row, "======>>>>>>editmony");
      this.dialogVisible = true;
      // this.form.roleNames = row.roleNames;
      console.log(this.form.roleNames);
      this.title = 2;
      // this.form.roleNames = this.roleNames;
      if (this.title == 2) {
        // row里面没有roleNames字段
        //const form = JSON.parse(JSON.stringify(row));
        const form = deepCopy(row);
        console.log(form, "form");
        this.form = {
          ...form,
          roleNames: [],
        };
        this.form.roleNames = [];
        //获取组织架构
        organizationtree().then((res) => {
          this.organizationalstructure = res.data;
          tcdate(this.organizationalstructure) 
          this.setupdepartments = res.data;
          console.log(res, "sssssss");
        });
        // postapi(`/api/app/abpuserdepartment/createmany?UserId=${this.form.id}`,{orgId:this.orgId[0]}).then(res=>{
        //   console.log(res,'wwwwwwwwwwwww');
        // })
        useraffiliation(this.form.id).then((res) => {
          console.log(res.data.items);
          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/${row.id}`).then(res =>{
          console.log(`/api/app/organization-units/organization-unit-by-user-id/${row.id}`,res)
          if(res.code != -1 && res.data.length > 0){
            this.orgId = [res.data[0].id]
          }
        })
       
        //获取科室权限 编辑
        getapi(
          `/api/app/abpuserdepartment/getuserdepartment?UserId=${row.id}`
        ).then((res) => {
          // default-checked-keys
          this.department = res.data;
          console.log(res, "科室");
        });
      }

      // 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();
      // });
      console.log(this.title);
      getbook().then((res) => {
        console.log(res, "===>>>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,
          //   };
          // });
          console.log("options", this.options);
        }
      });
      // console.log(row);
      // usersinits(row.id).then((res) => {
      //   this.orgId = res.data[res.data.length - 1].displayName;
      //   this.orgIds = res.data[0].displayName;
      //   let list = res.data;
      //   this.defaultKeys = list.map((item) => {
      //     return item.id;
      //   });
      //   console.log("defaultKeys", this.defaultKeys);
      // });
    },
    //分页
    handleSizeChange(v) {
      this.pages.MaxResultCount = v;
      this.getlist();
    },
    handleCurrentChange(v) {
      this.pages.SkipCount = v;
      this.getlist();
    },
  },
};
</script>
<style scoped>
@import "../../assets/css/global_table.css";
@import "../../assets/css/global_dialog.css";
@import "../../assets/css/global.css";

::v-deep .el-card {
  margin-top: -15px;
  /* background-color: #000; */
  border-radius: 15px;
}

/* ::v-deep .el-card__body {
 
  margin-top: -15px;
  border-radius: 15px;
} */
</style>
