<!--  -->
<template>
  <div class="userManger_box">
    <el-card :style="'height:' + fullHeight + 'px'">
      <div class="card_box">
        <!-- 组织 -->
        <div
          class="userManger_left"
          :style="'height:' + (fullHeight - 100) + 'px'"
        >
          <el-tree
            :data="data"
            :props="defaultProps"
            @node-click="handleNodeClick"
            v-loading="loading"
          ></el-tree>
        </div>

        <!-- 搜索和表格 -->
        <div
          class="userManger_right"
          :style="'height:' + (fullHeight - 100) + 'px'"
        >
          <!-- 搜索 -->
          <el-row>
            <el-col>
              <!-- 组织搜索 -->
              <div class="search_box">
                <el-input
                  size="mini"
                  placeholder="请输入用户姓名"
                  v-model.trim="nameVal"
                  @change="searchData"
                  clearable
                >
                </el-input>
                <el-input
                  size="mini"
                  placeholder="请输入手机号"
                  v-model.trim="phoneVal"
                  @change="searchData"
                  clearable
                >
                </el-input>
                <div class="btn_box">
                  <el-button type="primary" size="mini" @click="searchData"
                    >搜索</el-button
                  >
                  <el-button type="primary" size="mini" @click="addrRole"
                    >添加用户</el-button
                  >
                </div>
              </div>
            </el-col>
          </el-row>

          <!-- 表格 -->
          <el-table
            :data="tableData"
            v-loading="loading2"
            stripe
            style="width: 100%; height: 90%;"
          >
            <el-table-column prop="ind" label="序号" width="90">
            </el-table-column>
            <el-table-column prop="real_name" label="姓名" width="190">
            </el-table-column>
            <el-table-column prop="username" label="账号名称" width="200">
            </el-table-column>
            <el-table-column prop="mobile" label="手机号" width="120">
              <template slot-scope="scope">
                <span>{{ scope.row.mobile || "无" }}</span>
              </template>
            </el-table-column>
            <el-table-column
              :show-overflow-tooltip="true"
              prop="org_list"
              label="所属组织"
              width="280"
            >
              <template slot-scope="scope">
                <span v-for="(item, index) in scope.row.org_list" :key="index"
                  >{{ item.org_name }}
                  <span v-if="index !== scope.row.org_list.length - 1">、</span>
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="state" label="状态" width="120">
              <template slot-scope="scope">
                <span v-if="scope.row.state == '正常'">
                  <span
                    style="
                      width: 6px;
                      height: 6px;
                      background: #30a031;
                      border-radius: 50%;
                      display: inline-block;
                      margin: 0 0 2px 0;
                    "
                  ></span>
                  <span>正常</span>
                </span>
                <span v-if="scope.row.state == '已停用'">
                  <span
                    style="
                      width: 6px;
                      height: 6px;
                      background: #f93f3d;
                      border-radius: 50%;
                      display: inline-block;
                      margin: 0 0 2px 0;
                    "
                  ></span>
                  <span>停用</span>
                </span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="280">
              <template slot-scope="scope">
                <a
                  class="reset"
                  href="javascript:;"
                  @click="actionFunc(scope.row)"
                  >编辑</a
                >
                <i class="line"></i>
                <a
                  class="delete"
                  :style="
                    scope.row.state == '已停用'
                      ? 'color: #1890ff'
                      : 'color: #f56c6c;'
                  "
                  href="javascript:;"
                  @click="outUse(scope.row)"
                  >{{ scope.row.state == "已停用" ? "启用" : "停用" }}</a
                >
                <i class="line"></i>
                <a
                  class="reset"
                  href="javascript:;"
                  @click="resetPwd(scope.row)"
                  >重置密码</a
                >
                <i class="line"></i>
                <a
                  class="delete"
                  href="javascript:;"
                  @click="deleteFunc(scope.row)"
                  >删除</a
                >
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <el-pagination
            v-if="tableData.length !== 0"
            @current-change="changeList"
            background
            layout="prev, pager, next, jumper"
            :current-page="page"
            :total="pageSum"
          >
          </el-pagination>
        </div>
      </div>
    </el-card>

    <!-- 添加 - 编辑 用户 -->
    <el-dialog
      :title="tltData"
      :visible.sync="userVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="30%"
    >
      <el-form ref="form" :rules="rules" :model="form" label-width="150px">
        <el-form-item label="账号: " prop="user">
          <el-input
            style="width: 80%"
            size="mini"
            v-model.trim="form.user"
          ></el-input>
        </el-form-item>

        <el-form-item
          v-if="tltData == '添加用户'"
          label="密码: "
          prop="password"
        >
          <el-input
            style="width: 80%"
            size="mini"
            v-model.trim="form.password"
          ></el-input>
        </el-form-item>

        <el-form-item label="姓名: " prop="name">
          <el-input
            style="width: 80%"
            size="mini"
            v-model.trim="form.name"
          ></el-input>
        </el-form-item>

        <el-form-item label="隶属海关: " prop="judge">
          <!-- <el-cascader
            :change-on-select="true"
            filterable
            :v-model="form.judge"
            :key="refreshItem"
            :options="tissueList"
            @change="judgeData"
            :props="{
              multiple: true,
              label: 'org_name',
              value: 'id',
              children: 'childrens',
              checkStrictly: true
            }"
            clearable
          ></el-cascader> -->
          <el-cascader
            filterable
            @change="judgeData"
            :key="refreshItem"
            :change-on-select="true"
            v-model="form.judge"
            :options="tissueList"
            :props="{
              multiple: true,
              label: 'org_name',
              value: 'id',
              children: 'childrens',
              checkStrictly: true
            }"
            :clearable="true"
            placeholder="请选择隶属海关"
          ></el-cascader>
        </el-form-item>

        <el-form-item label="角色: " prop="role">
          <!-- <el-cascader
            filterable
            :v-model="form.role"
            :key="refreshItem"
            :options="roleData"
            @change="roleChange"
            :props="{
              value: 'id',
              label: 'role_name',
              multiple: true,
              emitPath: false,
              checkStrictly: true
            }"
            clearable
          ></el-cascader> -->

          <el-cascader
            filterable
            @change="roleChange"
            :key="refreshItem"
            :change-on-select="true"
            v-model="form.role"
            :options="roleData"
            :props="{
              value: 'id',
              label: 'role_name',
              multiple: true,
              emitPath: false,
              checkStrictly: true
            }"
            :clearable="true"
            placeholder="请选择角色"
          ></el-cascader>
        </el-form-item>

        <el-form-item label="手机号码: " prop="phone">
          <el-input
            style="width: 80%"
            size="mini"
            v-model.trim="form.phone"
          ></el-input>
        </el-form-item>

        <el-form-item label="邮箱: " prop="mailbox">
          <el-input
            style="width: 80%"
            size="mini"
            v-model.trim="form.mailbox"
          ></el-input>
        </el-form-item>

        <el-form-item
          v-if="tltData == '添加用户'"
          label="账号状态: "
          prop="state"
        >
          <el-select
            clearable
            size="mini"
            v-model="form.state"
            placeholder="请选择"
          >
            <el-option label="正常" value="1"></el-option>
            <el-option label="停用" value="4"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button size="small" type="primary" @click="submitForm"
            >确定</el-button
          >
          <el-button size="small" @click="resetForm">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //input验证 - 密码框 - 禁止输入汉字
    const checkPath = (rule, value, callback) => {
      var reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
      if (value == "") {
        callback(new Error("请输入密码"));
      }

      if (reg.test(value)) {
        callback(new Error("密码不能包含汉字！"));
      }

      if (value.indexOf("#") !== -1 || value.indexOf("@") !== -1) {
        callback();
      } else {
        callback(new Error("密码必须包含*#@_字符之一"));
      }
    };
    // input验证 - 验证手机号
    var checkphone = (rule, value, callback) => {
      if (value == "") {
        callback(new Error("请输入手机号"));
      } else if (!this.isCellPhone(value)) {
        //引入methods中封装的检查手机格式的方法
        callback(new Error("请输入正确的手机号!"));
      } else {
        callback();
      }
    };
    return {
      fullHeight: document.documentElement.clientHeight - 116, //

      loading: true, //加载 - 组织列表
      loading2: true, // 加载 - 表格列表

      // 树形图
      data: [],
      defaultProps: {
        children: "childrens",
        label: "org_name"
      },

      // 搜索
      nameVal: "",
      phoneVal: "",

      // 表格
      tableData: [],

      // 分页
      page: 1, //当前页码
      pageSum: 0, // 总数量

      // 弹框
      tltData: "添加用户",
      userVisible: false,
      form: {
        user: "", //账号
        password: "", // 密码
        name: "", // 姓名
        judge: [], // 隶属海关
        role: [], //角色
        phone: "", // 手机号码
        mailbox: "", //邮箱
        state: "" // 账号状态
      },
      rules: {
        user: [
          { required: true, message: "请输入账号", trigger: "blur" },
          { min: 3, max: 20, message: "长度在 3 到 20 位之间", trigger: "blur" }
        ],
        password: [
          { required: true, validator: checkPath, trigger: "blur" }
          // { validator: checkPath, trigger: "blur" }
        ],
        name: [
          { required: true, message: "请输入姓名", trigger: "blur" }
          //   { min: 3, max: 5, message: "长度在 1 到 15 个字符", trigger: "blur" },
        ],
        judge: [
          { required: true, message: "隶属海关，可多选", trigger: "change" }
          //   { min: 3, max: 5, message: "长度在 1 到 15 个字符", trigger: "blur" },
        ],
        role: [
          {
            required: true,
            message: "请选择角色，可多选",
            trigger: "change"
          }
          //   { min: 3, max: 5, message: "长度在 1 到 30 个字符", trigger: "blur" },
        ],
        phone: [{ required: true, validator: checkphone, trigger: "blur" }]
      },
      roleData: [], // 角色下拉框
      refreshItem: 0, //清除角色、组织值
      tissueList: [], // 组织下拉框
      editorObj: {}, //点击编辑选中当前的行数据
      org_id: "" //组织id
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    fullHeight(val) {
      //监控浏览器高度变化
      if (!this.timer) {
        this.fullHeight = val;
        this.timer = true;
        let that = this;
        setTimeout(function() {
          //防止过度调用监测事件，导致卡顿
          that.timer = false;
        }, 400);
      }
    },

    userVisible(val) {
      if (val == false) {
        // this.$refs["form"].resetFields();
        for (var key in this.form) {
          this.form[key] = "";
          // console.log(key)
        }
        this.refreshItem++;
      }
    }
  },
  //方法集合
  methods: {
    //动态获取浏览器高度
    get_boderHeight() {
      const that = this;
      window.onresize = () => {
        return (() => {
          window.fullHeight = document.documentElement.clientHeight;
          that.fullHeight = window.fullHeight;
        })();
      };
    },

    // 验证手机号是否正确
    isCellPhone(val) {
      if (!/^1(3|4|5|6|7|8)\d{9}$/.test(val)) {
        return false;
      } else {
        return true;
      }
    },

    // 树形图
    handleNodeClick(data) {
      this.org_id = data.id;
      this.loading2 = true;
      this.userListData();
    },

    // 编辑
    actionFunc(e) {
      this.tltData = "编辑用户";
      this.editorObj = e;

      this.form.judge = [];
      var orgList = []; // 组织
      var roleList = []; // 角色
      for (var i = 0; i < e.org_list.length; i++) {
        var arr = [e.org_list[i].org_id];
        orgList.push(arr);
      }
      if (e.parent_list.length != 0) {
        var data = e.parent_list;
        for (var i = 0; i < data.length; i++) {
          var data2 = data[i];
          for (var j = 0; j < data2.length; j++) {
            orgList[i].unshift(data2[j].org_id);
          }
        }
      }
      // 角色
      for (var x = 0; x < e.role_list.length; x++) {
        var a = [e.role_list[x].role_id];
        roleList.push(a);
      }

      this.form = {
        user: e.username,
        password: "",
        name: e.real_name,
        judge: orgList,
        role: roleList,
        phone: e.mobile,
        mailbox: e.email,
        state: e.state
      };
      this.userVisible = true;
    },
    // 停用
    outUse(data) {
      if (data.state == "已停用") {
        var msg = "启用";
      } else if (data.state == "正常") {
        var msg = "停用";
      }
      this.$confirm("此操作将" + msg + "该账号, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$axios({
            method: "POST",
            url: "/api/api_gateway?method=sysmenage.usermanager.user_disable",
            data: this.qs.stringify({
              user_id: data.user_id,
              state: msg == "启用" ? 1 : 4
            })
          }).then(res => {
            if (res.data.data == true) {
              this.$message({
                type: "success",
                message: "成功",
                duration: 1500
              });
              this.userListData();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },

    // 重置密码
    resetPwd(data) {
      this.$prompt("请输入新密码", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPlaceholder: "默认密码为@12345678",
        inputErrorMessage: "新密码格式不正确",
        inputValidator: val => {
          if (escape(val).indexOf("%u") != -1) {
            return "不能输入汉字！";
          } else if (val.split(" ").join("").length == 0) {
            return "不能输入空格！";
          }
        }
      })
        .then(({ value }) => {
          this.$axios({
            method: "POST",
            url:
              "/api/api_gateway?method=sysmenage.usermanager.password_modify",
            data: this.qs.stringify({
              user_id: data.user_id,
              password: value == null ? "@12345678" : value
            })
          }).then(res => {
            if (res.data.data == true) {
              this.$message({
                message: "成功!",
                type: "success",
                duration: 1500
              });
            }
            this.userListData();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消输入"
          });
        });
    },

    // 删除
    deleteFunc(data) {
      this.$confirm("此操作将永久删除该账号, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$axios({
            method: "POST",
            url: "/api/api_gateway?method=sysmenage.usermanager.user_delete",
            data: this.qs.stringify({
              user_id: data.user_id
            })
          }).then(res => {
            if (res.data.data == true) {
              this.$message({
                message: "成功!",
                type: "success",
                duration: 1500
              });
            } else {
              this.$message({
                message: "失败!",
                type: "error",
                duration: 1500
              });
            }
            this.loading2 = true;
            this.userListData();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },

    // 分页
    changeList(page) {
      this.loading2 = true;
      this.page = page;
      this.userListData();
    },

    // 搜索
    searchData() {
      this.loading2 = true;
      this.userListData();
    },

    // 添加用户
    addrRole() {
      this.tltData = "添加用户";
      this.userVisible = true;
    },

    // 添加 - 编辑 确定
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 处理隶属海关、角色
          var orgList = []; //隶属海关
          var roleList = []; // 角色
          for (var i = 0; i < this.form.judge.length; i++) {
            orgList.push(this.form.judge[i][this.form.judge[i].length - 1]);
          }
          for (var j = 0; j < this.form.role.length; j++) {
            roleList.push(this.form.role[j]);
          }
          if (this.tltData == "添加用户") {
            var postData = this.qs.stringify({
              username: this.form.user, // 登录账号 必
              real_name: this.form.name, // 用户名 必
              password: this.form.password, // 密码 必
              org_id_list: JSON.stringify(orgList), //组织id数组 必
              role_id_list: JSON.stringify(roleList), // 角色id数组 必
              state: this.form.state, //用户状态
              mobile: this.form.phone, // 手机号
              email: this.form.mailbox //邮箱地址
            });
            var url = "/api/api_gateway?method=sysmenage.usermanager.user_add";
          } else if (this.tltData == "编辑用户") {
            var postData = this.qs.stringify({
              user_id: this.editorObj.user_id, // 用户id 必
              real_name: this.form.name, // 用户名 必
              org_id_list: JSON.stringify(orgList), //组织id数组 必
              role_id_list: JSON.stringify(roleList), //角色id数组 必
              mobile: this.form.phone, //手机号
              email: this.form.mailbox //邮箱地址
            });
            var url =
              "/api/api_gateway?method=sysmenage.usermanager.user_modify";
          }
          this.$axios({
            method: "POST",
            url,
            data: postData
          }).then(res => {
            if (res.data.data == true) {
              this.$message({
                message: "成功!",
                type: "success",
                duration: 1500
              });

              this.$refs["form"].resetFields();
              this.userVisible = false;
              this.userListData();
            }
          });
        } else {
          return false;
        }
      });
    },
    // 取消
    resetForm() {
      this.$refs["form"].resetFields();
      this.refreshItem++;
      this.userVisible = false;
    },

    // 获取用户列表
    userListData() {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=sysmenage.usermanager.user_list",
        data: this.qs.stringify({
          page: this.page,
          page_item: "10",
          real_name: this.nameVal, // 用户名称
          mobile: this.phoneVal, //电话
          org_id: this.org_id
        })
      })
        .then(res => {
          if (res.data.data.page_item !== 0) {
            var data = res.data.data.page_list;
            var list = [];
            data.forEach((item, index) => {
              item.ind = index + 1;
              list.push(item);
            });
            this.tableData = list;
            this.pageSum = res.data.data.page_item;
          }
          this.loading2 = false;
        })
        .catch(err => {
          this.loading2 = false;
        });
    },

    // 获取左侧组织列表
    organizationData() {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=sysmenage.usermanager.org_list",
        data: this.qs.stringify({
          page: this.page,
          page_item: "100000000",
          org_name: ""
        })
      })
        .then(res => {
          if (res.data.data.page_list.length !== 0) {
            var obj = {
              org_name: "全部",
              id: ""
            };
            var list = res.data.data.page_list;
            this.tissueList = list; // 弹框组织列表
            var data = res.data.data.page_list;
            this.data = [obj, ...data]; // 左侧组织列表
          }
          this.loading = false;
        })
        .catch(err => {
          this.loading = false;
        });
    },

    // 获取角色列表
    roleAxios() {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=sysmenage.usermanager.role_list",
        data: this.qs.stringify({
          page: this.page,
          page_item: "10000000",
          role_name: ""
        })
      })
        .then(res => {
          if (res.data.data.total_item !== 0) {
            this.roleData = res.data.data.page_list;
          }
        })
        .catch(err => {});
    },
    judgeData(item) {
      this.form.judge = item;
    },
    roleChange(item) {
      this.form.role = item;
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.loading = true; // 加载 - 组织列表
    this.loading2 = true; // 加载 - 表格列表
    this.userListData(); //表格数据
    this.organizationData(); //左侧组织数据
    this.roleAxios(); // 角色列表
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {} //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang="less" scoped>
.userManger_box {
  .card_box {
    display: flex;
    width: 100%;
    // 树形图
    .userManger_left {
      width: 19%;
      margin: 0 15px 0 0;
      padding: 5px;
      border: 1px solid #eeeeee;
      border-radius: 5px;
      overflow: hidden;
      overflow-y: auto;
    }

    // 搜索和表格
    .userManger_right {
      width: 80%;
      //   border: 1px solid red;

      // 搜索
      .search_box {
        display: flex;
        /deep/.el-input {
          width: 20%;
          margin: 0 15px 0 0;
        }
        .btn_box {
        }
      }
      a {
        text-decoration: none;
      }
      .reset {
        color: #1890ff;
      }
      .delete {
        color: #f56c6c;
      }
      .line {
        display: inline-block;
        width: 1px;
        background: rgba(0, 0, 0, 0.09);
        margin: 0 11px;
        height: 14px;
      }
    }
  }

  /deep/.el-select {
    width: 80%;
  }

  /deep/.el-cascader {
    width: 80%;
  }
}
</style>
