<template>
  <div style="display: flex">
    <org-tree v-if="$store.state.user.prntId == '1'"></org-tree>
    <div
      :style="$store.state.user.prntId == '1' ? 'width: 82%' : 'width: 100%'"
      class="common-box"
    >
      <!--条件-->
      <el-form :model="listQuery" ref="queryForm" :inline="true">
        <el-form-item label="用户账号">
          <el-input
            v-model="listQuery.loginId"
            placeholder="请输入用户账号"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户名称">
          <el-input
            v-model="listQuery.userName"
            placeholder="请输入用户名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="联系方式">
          <el-input
            v-model="listQuery.coninfo"
            placeholder="请输入联系方式"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getData('search')">查询 </el-button>
          <el-button @click="reset()">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="right-button">
        <el-button
          v-if="hasPerm('system:users:add') && !addSon"
          class="lake-Blue"
          type="primary"
          icon="el-icon-plus"
          @click="handleAddOrEdit(0, null, 'create')"
          >新增
        </el-button>
        <el-button
          v-if="addSon"
          type="primary"
          plain
          icon="el-icon-plus"
          @click="handleAddOrEdit(0, null, 'createself')"
          >新增子账号
        </el-button>
      </div>
      <!--列表-->
      <div>
        <el-table
          v-loading="listLoading"
          element-loading-text="加载中"
          :data="list"
          fit
          stripe
          border
        >
          <template slot="empty">
            <img src="@/assets/nopage.png" alt />
            <p>暂无数据</p>
          </template>
          <el-table-column
            fixed
            type="index"
            label="序号"
            width="60"
          ></el-table-column>
          <el-table-column
            label="父级编码"
            align="center"
            prop="prntId"
            v-if="tableShow"
          />
          <el-table-column
            label="用户编码"
            align="center"
            prop="userId"
            v-if="tableShow"
          />
          <el-table-column
            label="用户名称"
            align="center"
            prop="userName"
            min-width="150"
          />
          <el-table-column
            label="用户账号"
            align="center"
            prop="loginId"
            width="100"
          />
          <el-table-column label="机构名称" prop="orgName" width="150" />
          <el-table-column
            label="联系方式"
            align="center"
            prop="coninfo"
            width="100"
          />
          <el-table-column align="center" label="年龄" width="80" prop="age" />
          <el-table-column align="center" label="性别" width="80" prop="gend" />
          <el-table-column label="创建时间" width="140" prop="crteTime" />
          <el-table-column label="修改时间" width="140" prop="lstUpdTime" />
          <el-table-column label="说明" prop="dscr" />

          <el-table-column fixed="right" label="操作" width="220">
            <template
              slot-scope="scope"
              v-if="scope.row.loginId !== 'super-admin'"
            >
              <el-button
                class="cyan"
                type="text"
                @click="handleAddOrEdit(scope.$index, scope.row, 'update')"
                >编辑</el-button
              >
              <el-button
                v-if="!addSon"
                type="text"
                class="orange"
                @click="handleAddOrEdit(scope.$index, scope.row, 'createson')"
                >新增子账号</el-button
              >
              <el-button
                class="red"
                type="text"
                @click="handleDelete(scope.row, 'deleted')"
                >删除</el-button
              >
              <el-dropdown
                @command="(command) => handleCommand(command, scope.row)"
              >
                <span class="el-dropdown-link">
                  <el-button style="margin-left: 10px" type="text"
                    >更多
                  </el-button>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="setRole">
                    设置角色
                  </el-dropdown-item>
                  <el-dropdown-item command="resetPass" divided
                    >重置密码
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!--分页-->
      <yl-pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.current"
        :limit.sync="listQuery.size"
        @pagination="getData"
      />
    </div>

    <!--添加/修改-->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      width="420px"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="80px"
        style="width: 370px; margin-left: 10px"
      >
        <el-form-item label="用户名称" prop="userName">
          <el-input v-model.trim="temp.userName" />
        </el-form-item>
        <el-form-item label="所属机构" prop="orgId" v-if="orgform">
          <el-input
            disabled
            v-model.trim="temp.orgName"
            style="width: 210px; margin-right: 3px"
          />
          <el-button type="primary" icon="el-icon-plus" @click="chooseOrg"
            >选择</el-button
          >
        </el-form-item>
        <el-form-item label="联系方式" prop="coninfo">
          <el-input v-model.trim="temp.coninfo" />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="temp.age"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="temp.gend">
            <el-radio label="男"></el-radio>
            <el-radio label="女"></el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="说明">
          <el-input type="textarea" v-model.trim="temp.dscr" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="commitData()" :loading="btLoading1">{{
          btLoading1 ? "确认中" : "确认"
        }}</el-button>
      </div>
    </el-dialog>

    <!--用户id，密码对话框-->
    <el-dialog title="提示" :visible.sync="passFormVisible" width="50%">
      <el-alert
        title="请保存用户编码和密码,方便后续进行登录！！！"
        type="warning"
        show-icon
        style="margin-bottom: 20px"
      >
      </el-alert>
      <el-descriptions class="margin-top" title="" :column="1" border>
        <el-descriptions-item>
          <template slot="label"> 用户名称 </template>
          {{ passData.userName }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label"> 用户编码 </template>
          {{ passData.loginId }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template slot="label"> 密码 </template>
          {{ passData.pwd }}
        </el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="passFormVisible = false"
          >关闭</el-button
        >
      </div>
    </el-dialog>

    <!--设置角色对话框-->
    <el-dialog title="设置角色" :visible.sync="roleFormVisible" width="610px">
      <el-transfer
        filterable
        :filter-method="filterMethod"
        filter-placeholder="请输入角色名称"
        v-model="roles"
        :data="newRoleList"
        :titles="['可选角色', '已选角色']"
      >
      </el-transfer>
      <div slot="footer" class="dialog-footer">
        <el-button @click="roleFormVisible = false">取消</el-button>
        <el-button type="primary" @click="setRole()" :loading="btLoading2">{{
          btLoading2 ? "确认中" : "确认"
        }}</el-button>
      </div>
    </el-dialog>

    <!--选择机构-->
    <el-dialog
      v-if="dialogOrgFormVisible"
      title="选择机构"
      :visible.sync="dialogOrgFormVisible"
      width="450px"
    >
      <el-tree
        ref="tree"
        :data="treeList"
        :props="defaultProps"
        default-expand-all="true"
        highlight-current="true"
        :filter-node-method="filterNode"
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ node.label }}</span>
          <span>
            <el-button
              plain
              type="primary"
              size="mini"
              @click.stop="() => chooseSumbit(node, data)"
            >
              选择
            </el-button>
          </span>
        </span>
      </el-tree>
    </el-dialog>
  </div>
</template>

<script>
import bus from "@/views/bus";
import {
  setUser,
  resetPass,
  getUserData,
  getRoleData,
  setUserRole
} from "@/api/system/users";
import orgTree from "@/views/components/org-tree";
import ylPagination from "@/components/yl-pagination";
import Organization from "@/views/page/system/users/components/organization";

export default {
  components: {
    ylPagination,
    Organization,
    orgTree
  },

  watch: {},

  data() {
    return {
      // 新增子账号
      addSon: false,
      // 表单新增所属机构隐藏
      orgform: true,
      // 表格
      tableShow: true,
      defaultProps: {
        children: "child",
        label: "orgName"
      },
      btLoading1: false,
      btLoading2: false,
      // 回显机构名称
      orgName: "",
      // 选择机构对话框
      dialogOrgFormVisible: false,
      // 当前用户id
      currentUserId: "",
      // 角色列表
      roleList: [],
      newRoleList: [],
      // 选中的角色
      roles: [],
      filterMethod(query, item) {
        return item.label.indexOf(query) > -1;
      },
      // 打开角色设置对话框
      roleFormVisible: false,
      // 机构列表
      organList: [],
      // 打开用户id,密码对话框
      passFormVisible: false,
      // 用户id,密码
      passData: {},
      list: [], //列表
      total: 0, //分页
      listLoading: false,
      listQuery: {
        //条件查询
        userName: "",
        current: 1,
        size: 10,
        loginId: "",
        orgnId: "",
        coninfo: ""
      },
      searchForm: {
        current: 1,
        size: 10,
        orgName: "",
        orgId: ""
      },
      // orgData: [],
      loadingsearch: false,
      rolesValue: [],
      dialogFormVisible: false, //是否对话框
      dialogStatus: "",
      textMap: {
        update: "编辑",
        create: "添加",
        createson: "新增子账号",
        createself: "新增子账号"
      },
      temp: {
        //表单
        orgName: "",
        orgId: ""
      },
      dialogRoleFormVisible: false, //角色对话框
      tempRole: {},
      rules: {
        userName: [
          {
            required: true,
            message: "用户名称不能为空",
            trigger: "blur"
          },
          {
            min: 2,
            max: 20,
            message: "用户名称长度必须介于 2 和 20 之间",
            trigger: "blur"
          }
        ],
        orgId: [
          {
            required: true,
            message: "请选择所属机构",
            trigger: "change"
          }
        ],
        age: [
          {
            required: false,
            message: "年龄不能为空",
            trigger: "blur"
          },
          {
            pattern: /^(?:[1-9][0-9]?|1[01][0-9]|120)$/,
            message: "请输入正确的格式",
            trigger: "blur"
          }
        ],
        coninfo: [
          {
            required: true,
            message: "联系方式不能为空",
            trigger: "blur"
          },
          {
            pattern: /^1(?:3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8\d|9\d)\d{8}$/,
            message: "请输入正确的格式",
            trigger: "blur"
          }
        ]
      },
      treeList: []
    };
  },

  created() {
    this.getData();
    // 如果为超级管理员的情况
    if (this.$store.state.user.prntId == "1") {
      //新增子账号按钮
      this.addSon = false;
      // 所属机构
      this.orgform = true;
      this.tableShow = true;
    } else {
      // 新增子账号按钮
      this.addSon = true;
      // 所属机构
      this.orgform = false;
      this.tableShow = false;
    }
  },

  mounted() {
    bus.$on("orgName", (val) => {
      this.temp.orgName = val;
      this.listQuery.orgName = this.temp.orgName;
    });
    bus.$on("orgId", (val) => {
      this.temp.orgId = val;
      this.listQuery.orgnId = this.temp.orgId;
      this.getData();
    });
    bus.$on("treeList", (val) => {
      this.treeList = val;
    });
  },

  methods: {
    filterNode(value, data) {
      if (!value) return true;
      return data.orgName.indexOf(value) !== -1;
    },

    chooseSumbit(node, data) {
      this.temp.orgId = data.orgId;
      this.temp.orgName = data.orgName;
      this.dialogOrgFormVisible = false;
    },

    // 更多
    handleCommand(command, row) {
      if (command == "setRole") {
        this.setRoleBox(row);
      } else if (command == "resetPass") {
        this.editPass(row);
      }
    },
    // 选择机构
    chooseOrg() {
      this.dialogOrgFormVisible = true;
    },

    // 获取到选中的机构
    orgSubmit(orgRadio, orgName) {
      this.temp.orgId = orgRadio;
      this.orgName = orgName;
      this.dialogOrgFormVisible = false;
    },

    // 重置密码
    editPass(row) {
      this.$confirm("确认重置密码", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let data = { id: row.id };
        resetPass(data).then((response) => {
          this.$message({
            message: "操作成功",
            type: "success"
          });
          this.passData = {
            loginId: row.loginId,
            pwd: response.data,
            userName: row.userName
          };
          this.passFormVisible = true;
        });
      });
    },

    // 打开设置角色对话框
    setRoleBox(row) {
      this.currentUserId = row.userId;
      this.roles = [];
      getRoleData({ userId: row.userId, current: 1, size: 1000 }).then(
        (response) => {
          this.roleList = response.data.records;
          this.newRoleList = [];
          this.roleList.forEach((item, index) => {
            this.newRoleList.push({
              label: item.roleName,
              key: item.roleId
            });
            if (item.cho == "0") {
              this.roles.push(item.roleId);
            }
          });
          this.roleFormVisible = true;
        }
      );
    },

    // 去重
    duplicateRemoval(tempArr) {
      for (let i = 0; i < tempArr.length; i++) {
        for (let j = i + 1; j < tempArr.length; j++) {
          if (tempArr[i].roleId == tempArr[j].roleId) {
            tempArr.splice(j, 1);
            j--;
          }
        }
      }
      return tempArr;
    },

    // 设置角色
    setRole() {
      this.$confirm("确认提交", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.btLoading2 = true;
        let newRoles = [];
        this.roles.forEach((item, index) => {
          newRoles.push({ roleId: item, userId: this.currentUserId });
        });
        let newData = this.duplicateRemoval(newRoles);

        setUserRole(newData)
          .then((response) => {
            this.$message({
              message: "操作成功",
              type: "success"
            });
            this.btLoading2 = false;
            this.roleFormVisible = false;
          })
          .catch(() => {
            this.btLoading2 = false;
          });
      });
    },

    // 重置页面
    reset() {
      this.listQuery.loginId = "";
      this.listQuery.userName = "";
      this.listQuery.coninfo = "";
      this.listQuery.orgId = "";
      this.getData();
    },

    //获取列表数据
    getData(type) {
      if (type == "search") {
        this.listQuery.current = 1;
      }
      this.listLoading = true;
      getUserData(this.listQuery)
        .then((response) => {
          this.list = response.data.records;
          this.total = response.data.total;
          this.listLoading = false;
        })
        .catch((err) => {
          this.listLoading = false;
        });
    },

    //提交表单数据
    commitData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.$confirm("确认提交", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            this.btLoading1 = true;
            setUser(this.temp)
              .then((response) => {
                this.btLoading1 = false;
                this.$message({
                  message: "操作成功",
                  type: "success"
                });
                this.dialogFormVisible = false;
                if (
                  this.dialogStatus === "create" ||
                  this.dialogStatus === "createson" ||
                  this.dialogStatus === "createself"
                ) {
                  this.passData = {
                    loginId: response.data.loginId,
                    pwd: response.data.pwd,
                    userName: this.temp.userName
                  };
                  this.passFormVisible = true;
                }
                this.getData();
              })
              .catch(() => {
                this.btLoading1 = false;
              });
          });
        }
      });
    },

    // 打开添加/修改对话框
    handleAddOrEdit(index, row, type) {
      this.orgName = "";
      this.temp.orgId = "";
      //修改对话框
      if (type === "update") {
        if (row.prntId == "0") {
          this.orgform = true;
        } else {
          this.orgform = false;
        }
        this.temp = {
          id: row.id,
          userName: row.userName,
          orgId: row.orgId,
          orgName: row.orgName,
          age: row.age,
          gend: row.gend,
          coninfo: row.coninfo,
          dscr: row.dscr,
          type: "updt"
        };
      } else if (type === "createson") {
        this.orgform = false;
        this.temp = {
          prntId: row.userId,
          id: "",
          userName: "",
          age: "",
          gend: "",
          coninfo: "",
          dscr: "",
          type: "add"
        };
      } else if (type == "createself") {
        this.orgform = false;
        this.temp = {
          prntId: this.$store.state.user.userId,
          id: "",
          userName: "",
          age: "",
          gend: "",
          coninfo: "",
          dscr: "",
          type: "add"
        };
      } else {
        this.orgform = true;
        this.temp = {
          id: "",
          userName: "",
          orgId: this.listQuery.orgnId,
          orgName: this.listQuery.orgName,
          age: "",
          gend: "",
          coninfo: "",
          dscr: "",
          type: "add"
        };
      }
      this.dialogStatus = type;
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },

    //删除
    handleDelete(row, status) {
      this.$confirm("确认删除", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.temp = {
          id: row.id,
          userName: row.userName,
          orgId: row.orgId,
          age: row.age,
          gend: row.gend,
          coninfo: row.coninfo,
          dscr: row.dscr,
          type: "del"
        };
        setUser(this.temp).then((response) => {
          this.$message({
            message: "操作成功",
            type: "success"
          });
          //  解决element el-pagination分页最后一页数据清空了页码显示正确，但是列表为空
          const totalPage = Math.ceil((this.total - 1) / this.listQuery.size);
          const currentPage =
            this.listQuery.current > totalPage
              ? totalPage
              : this.listQuery.current;
          this.listQuery.current = currentPage < 1 ? 1 : currentPage;

          this.getData();
        });
      });
    }
  }
};
</script>

<style scoped lang="scss">
::v-deep .el-transfer-panel__body {
  height: 520px;
}
::v-deep .el-transfer-panel__list.is-filterable {
  height: 100%;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
::v-deep .el-tree-node__content {
  height: 38px;
}
</style>
