<template>
  <div id="index">
    <el-row>
      <el-col :span="24" class="main">
        <el-col :span="24" class="one">
          <!-- <el-form
            :model="queryParams"
            ref="queryForm"
            :inline="true"
            v-show="showSearch"
            label-width="68px"
          >
            <el-form-item label="用户名称" prop="userName">
              <el-input
                v-model="queryParams.userName"
                placeholder="请输入用户名称"
                clearable
                size="small"
                style="width: 240px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input
                v-model="queryParams.phonenumber"
                placeholder="请输入手机号码"
                clearable
                size="small"
                style="width: 240px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="handleQuery"
                >搜索</el-button
              >
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
                >重置</el-button
              >
            </el-form-item>
          </el-form> -->
        </el-col>
        <el-col :span="24" class="two">
          <el-col :span="24" class="two_1">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              >新增</el-button
            >
          </el-col>
          <el-col :span="24" class="two_2">
            <el-table
              :data="list"
              border
              style="width: 100%"
              :header-cell-style="{ 'text-align': 'center' }"
              :cell-style="{ 'text-align': 'center' }"
            >
              <el-table-column
                prop="userName"
                label="用户名称"
                show-overflow-tooltip
              >
              </el-table-column>
              <el-table-column
                prop="nickName"
                label="用户昵称"
                show-overflow-tooltip
              >
              </el-table-column>
              <el-table-column
                prop="phonenumber"
                label="手机号码"
                show-overflow-tooltip
              >
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="toEdit(scope.row)"
                    >修改</el-button
                  >
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="toDel(scope.row)"
                    >删除</el-button
                  >
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-key"
                    @click="toPwd(scope.row)"
                    >重置</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <el-col :span="24" class="page">
              <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[10, 20, 30, 50]"
                :page-size="limit"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                background
              >
              </el-pagination>
            </el-col>
          </el-col>
        </el-col>
      </el-col>
    </el-row>
    <el-dialog
      :title="dialog.title"
      :visible.sync="dialog.show"
      width="40%"
      :before-close="toClose"
      :close-on-click-modal="false"
      custom-class="dialog"
    >
      <div class="info">
        <form-1
          :form="form"
          :deptOptions="deptOptions"
          :sexOptions="sexOptions"
          :statusOptions="statusOptions"
          :postOptions="postOptions"
          :roleOptions="roleOptions"
          @onSubmit="onSubmit"
          @resetForm="toClose"
        ></form-1>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listUser,
  getUser,
  delUser,
  addUser,
  updateUser,
  resetUserPwd,
} from "@/api/system/user";
import form1 from "./parts/form-1.vue";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { mapState, mapGetters, createNamespacedHelpers } from "vuex";
const { mapActions: merits_user } = createNamespacedHelpers("merits_user");
const { mapActions: role_relation } = createNamespacedHelpers("role_relation");
export default {
  name: "index",
  props: {},
  components: { form1, Treeselect },
  data: function () {
    return {
      // 显示搜索条件
      showSearch: true,
      // 查询
      queryParams: {},
      // 列表
      list: [],
      total: 0,
      dialog: { title: "新增用户", show: false },
      // 添加
      form: { status: "0" },
      // 默认密码
      initPassword: undefined,
      // 归属部门
      deptOptions: undefined,
      // 性别状态字典
      sexOptions: [],
      // 状态数据字典
      statusOptions: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 分页
      currentPage: 1,
      limit: 10,
    };
  },
  created() {
    this.searchOther();
    this.getList();
    this.getConfigKey("sys.user.initPassword").then((response) => {
      this.initPassword = response.msg;
    });
  },
  methods: {
    ...merits_user(["query", "create", "delete"]),
    ...role_relation({ roleQuery: "query" }),
    async getList({ skip = 0, limit = this.limit, ...info } = {}) {
      info.superior_id = this.user_id;
      let res = await this.query({ skip, limit, ...info });
      if (this.$checkRes(res)) {
        this.$set(this, `list`, res.data);
        this.$set(this, `total`, res.total);
      }
    },
    // 修改信息
    toEdit(row) {
      const userId = row.userId;
      getUser(userId).then((response) => {
        this.form = response.data;
        this.postOptions = response.posts;
        this.form.postIds = response.postIds;
        this.form.roleIds = response.roleIds;
        this.dialog = { title: "修改信息", show: true };
      });
    },
    // 删除信息
    async toDel(row) {
      const userIds = row.userId || this.ids;
      this.$confirm("是否确认删除数据项吗?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delUser(userIds);
        })
        .then(async () => {
          let res = await this.delete(userIds);
          if (this.$checkRes(res)) {
            this.handleQuery();
            this.msgSuccess("删除成功");
          }
        })
        .catch(() => {});
    },
    // 重置密码
    toPwd(row) {
      this.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(({ value }) => {
          resetUserPwd(row.userId, value).then((response) => {
            this.msgSuccess("修改成功，新密码是：" + value);
          });
        })
        .catch(() => {});
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 新增
    handleAdd() {
      this.form.password = this.initPassword;
      this.dialog = { title: "新增用户", show: true };
    },
    // 提交
    onSubmit({ data }) {
      if (data && data.userId) {
        delete data.createTime;
        delete data.updateTime;
        updateUser(data).then((response) => {
          this.msgSuccess("修改成功");
          this.toClose();
          this.getList();
        });
      } else {
        addUser(data).then((response) => {
          if (response.code === 200) {
            listUser(this.addDateRange({ userName: data.userName })).then(
              async (res) => {
                let p1 = res.rows.find((i) => i.userName === data.userName);
                if (p1) {
                  let p2 = { user_id: p1.userId, superior_id: this.user_id };
                  let p3 = await this.create(p2);
                  if (this.$checkRes(p3)) {
                    this.msgSuccess("新增成功");
                    this.toClose();
                    this.getList();
                  }
                }
              }
            );
          }
        });
      }
    },
    // 其他信息
    async searchOther() {
      treeselect().then((response) => {
        this.deptOptions = response.data;
      });
      this.getDicts("sys_user_sex").then((response) => {
        this.sexOptions = response.data;
      });
      this.getDicts("sys_normal_disable").then((response) => {
        this.statusOptions = response.data;
      });
      getUser().then(async (response) => {
        this.postOptions = response.posts;
        let res = await this.roleQuery();
        if (this.$checkRes(res)) {
          let levelInfo = res.data.relation.find(
            (i) => i.roleKey == this.roles[0]
          );
          if (levelInfo) {
            let nextLevel = parseInt(levelInfo.level) + 1;
            let p1 = res.data.relation.filter((i) => i.level == nextLevel)[0];
            let roleList = response.roles.filter(
              (i) => i.roleKey == p1.roleKey
            );
            if (roleList) this.roleOptions = roleList;
          }
        }
      });
    },
    // 关闭
    toClose() {
      this.form = { status: "0" };
      this.dialog = { title: "新增用户", show: false };
    },
    // 分页
    handleSizeChange(val) {
      this.$set(this, `limit`, val);
      this.getList();
    },
    handleCurrentChange(val) {
      this.getList({ skip: (val - 1) * this.limit });
    },
  },

  computed: {
    ...mapGetters(["user_id", "roles"]),
  },
  metaInfo() {
    return { title: this.$route.meta.title };
  },
  watch: {
    test: {
      deep: true,
      immediate: true,
      handler(val) {},
    },
  },
};
</script>

<style lang="scss" scoped>
.main {
  padding: 25px 30px 30px;
  .two {
    .two_1 {
      margin: 0 0 10px 0;
    }
  }
}
.page {
  text-align: right;
  margin: 10px 0 0 0;
}
.dialog {
  .info {
    height: 430px;
    overflow-y: auto;
  }
}
</style>
