<template>
  <div class="main-contain">
    <div class="position">
      <bread-crumb :crumbs="crumbs"></bread-crumb>
      <!-- <router-link to="/role/admin/create"> -->
      <el-button
        type="primary"
        size="small"
        icon="el-icon-circle-plus-outline"
        style="float:right;"
        @click="openForm(0)"
        >新增</el-button
      >
      <!-- </router-link> -->
    </div>
    <div class="app-container">
      <el-table
        :row-style="{ color: '#303133' }"
        :header-cell-style="{
          backgroundColor: 'rgb(245, 247, 250)',
          color: '#606266'
        }"
        style="width:100%;"
        ref="table"
        border
        :data="admins"
        v-loading="is_loading_admins"
      >
        <el-table-column
          label="用户名"
          prop="user_name"
          min-width="160"
          align="center"
        ></el-table-column>
        <el-table-column
          label="最后登录IP"
          prop="ip"
          min-width="150"
          align="center"
        ></el-table-column>
        <el-table-column
          label="最后登录时间"
          prop="last_login_time"
          min-width="170"
          align="center"
        >
          <template slot-scope="scope">
            <span>{{
              scope.row.last_login_time == 0
                ? ""
                : _parseTime(scope.row.last_login_time, "{y}-{m}-{d} {h}:{i}")
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="角色"
          prop="role_name"
          min-width="160"
          align="center"
        ></el-table-column>
        <el-table-column
          label="职称"
          prop="title_name"
          min-width="160"
          align="center"
        ></el-table-column>
        <el-table-column label="状态" min-width="100" align="center">
          <template slot-scope="scope">
            <div
              v-if="scope.row.status == 1"
              style="color: #67C23A; font-size:20px;"
            >
              <li class="el-icon-success"></li>
            </div>
            <div v-else style="color: #F56C6C; font-size:20px;">
              <li class="el-icon-error"></li>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template slot-scope="scope">
            <!-- <router-link :to="{ path:'/role/admin/edit', query:{ id:scope.row.user_id }}"> -->
            <el-tooltip
              class="item"
              effect="dark"
              content="编辑"
              placement="top"
            >
              <el-button
                type="primary"
                icon="el-icon-edit-outline"
                size="small"
                @click="openForm(scope.row.user_id)"
              ></el-button>
            </el-tooltip>
            <!-- </router-link> -->
            <el-tooltip
              class="item"
              effect="dark"
              content="移除"
              placement="top"
            >
              <el-button
                type="danger"
                size="small"
                icon="el-icon-delete"
                v-if="scope.row.status == 1 && org.creator != scope.row.user_id && (scope.row.user_id != local_user_id )"
                @click="disableAdminAction(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="恢复"
              placement="top"
            >
              <el-button
                size="small"
                type="info"
                icon="el-icon-refresh"
                v-if="scope.row.status == 0 && org.creator != scope.row.user_id  && (scope.row.user_id != local_user_id )"
                @click="recoverAdminAction(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-row style="margin-top: 15px;" v-if="admin_total_count > 10">
        <el-col :span="24">
          <el-pagination
            :total="admin_total_count"
            :current-page.sync="current_page"
            @current-change="pageChange"
            :page-size="10"
            layout="total, prev, pager, next, jumper"
          ></el-pagination>
        </el-col>
      </el-row>
      <admin-info-form ref="admininfoform"></admin-info-form>
    </div>
  </div>
</template>

<script>
import { adminMainView, getAdmins, setAdminStatus } from "@/api/role/admin";
import { getRoles } from "@/api/role/role";

import { parseTime } from "@/utils";
import BreadCrumb from "@/xt_pages/components/bread-crumb";
import AdminInfoForm from "./components/AdminInfoForm";

export default {
  name: "adminManage",
  data() {
    return {
      crumbs: [
        { path: false, name: "权限管理" },
        { path: false, name: "用户管理" }
      ],
      is_loading_admins: true,
      admins: [], // [{user_id, user_name, role_name, title_name, ip, last_login_time, status}]
      admin_total_count: 0,
      current_page: 1,
      roles:[],
      is_exist_role: false,
      org: null,
      isSubSuperAdmin:false,

      local_user_id: 0,
    };
  },
  components: {
    BreadCrumb,
    AdminInfoForm
  },
  created: function() {
    this.local_user_id = this.$store.getters.xt_user.user.id
    this.local_user_id = 597
    let page = 1
    this.getRoles(page)
    adminMainView()
      .then(rs => {
        this.is_loading_admins = false;
        var resp = rs.data;
        if (resp.state === 1) {

          this.admins.push(...resp.data.admins);
          this.admin_total_count = resp.data.total_count;
          this.is_exist_role = resp.data.is_exist_role;
          this.current_page = 1;
          this.org = resp.data.org
          this.isSubSuperAdmin = resp.data.isSubSuperAdmin

          //能进入当前页面的角色只有超级管理员和子管理员，如果当前角色是子管理员，需要把超级管理员和其他子管理员的信息去除，子管理员不能编辑超级管理员和其他子管理员信息，
          if(this.isSubSuperAdmin) {
            //去除管理员信息
            for (let i = 0; i < this.admins.length; i++){
              if (this.admins[i].user_id == this.org.creator) {
                this.admins.splice(i, 1)
                i--
              }
            }

            //去除其他子管理员信息
            for (let i = 0; i < this.admins.length; i++){
              if (this.admins[i].user_id  != this.local_user_id && this.admins[i].is_sub_super_admin) { //将自己排除在外
                console.log(this.admins[i])

                this.admins.splice(i, 1)
                i--
              }
            }

          }
        } else {
          this.$message.error(resp.msg);
        }
      })
      .catch(err => {
        this.is_loading_admins = false;
        this.$message.error(err);
      });
  },
  computed: {
    should_update_admins() {
      return this.$store.getters.xt_role_temps.did_admins_changed;
    }
  },
  methods: {
    getRoles(page){
      getRoles(page)
        .then(rs => {
          this.loading_roles = false;
          const resp = rs.data;
          if (resp.state === 1) {
            this.roles.push(...resp.data.roles);
          } else {
            this.$message.error(resp.msg);
          }
        })
        .catch(err => {
          this.loading_roles = false;
          this.$message.error(err);
        });
    },
    openForm(adminId) {
      this.$refs["admininfoform"].open(adminId,this.roles);
    },
    _parseTime(time, format) {
      return parseTime(time, format);
    },
    requestAdminsWithPage: function(page) {
      this.admins.splice(0, this.admins.length);
      this.is_loading_admins = true;
      getAdmins(page)
        .then(rs => {
          this.is_loading_admins = false;
          const resp = rs.data;
          console.log(resp);
          if (resp.state === 1) {
            this.admins.push(...resp.data.admins);
            this.admin_total_count = resp.data.total_count;
          } else {
            this.$message.error(resp.msg);
          }
        })
        .catch(err => {
          this.is_loading_admins = false;
          this.$message.error(err);
        });
    },
    addAdminAction: function() {
      this.$router.push({ path: "/role/admin/create" });
    },
    disableAdminAction: function(row) {
      this.$msgbox({
        title: "提示",
        message: "是否确定要移除该用户",
        showCancelButton: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        beforeClose: (action, instance, done) => {
          if (action === "confirm") {
            instance.confirmButtonLoading = true;
            instance.confirmButtonText = "删除中...";

            setAdminStatus(row.user_id, false)
              .then(rs => {
                done();
                instance.confirmButtonLoading = false;

                const resp = rs.data;
                if (resp.state === 1) {
                  row.status = 0;
                } else {
                  this.$message.error(resp.msg);
                }
              })
              .catch(err => {
                done();
                instance.confirmButtonLoading = false;
                this.$message.error(err);
              });
          } else {
            done();
          }
        }
      });
    },
    recoverAdminAction: function(row) {
      const loading = this.$loading({
        lock: true,
        text: "正在恢复管理员...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });

      setAdminStatus(row.user_id, true)
        .then(rs => {
          loading.close();

          const resp = rs.data;
          if (resp.state === 1) {
            row.status = 1;
          } else {
            this.$message.error(resp.msg);
          }
        })
        .catch(err => {
          loading.close();
          this.$message.error(err);
        });
    },
    pageChange: function(nextPage) {
      this.requestAdminsWithPage(nextPage);
    }
  },
  watch: {
    should_update_admins(should_change) {
      if (should_change) {
        this.requestAdminsWithPage(this.current_page);
      }
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.el-button + .el-button {
  margin-left: 0 !important;
}
</style>
<style>
.el-table td,
.el-table th.is-leaf,
.el-table--border,
.el-table--group {
  border-color: #d0d3da;
}
.el-table--border::after,
.el-table--group::after,
.el-table::before {
  background-color: #d0d3da;
}
</style>
