<!--管理员管理-->
<template>
  <div class="index-home">
    <div v-loading.fullscreen.lock="loadingFull" />
    <div class="search">
      <el-form
        ref="searchParams"
        :model="searchParams"
        label-width="80px"
      >
        <el-input
          v-model="searchParams.name"
          placeholder="姓名"
          clearable
        ></el-input>
        <el-input
          v-model="searchParams.account"
          placeholder="账号"
          clearable
        ></el-input>
        <el-select
          v-model="searchParams.is_admin"
          placeholder="请选择"
          clearable
        >
          <el-option
            v-for="item in isAdmin"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>

        <el-button
          type="primary"
          @click="searchList"
          icon="el-icon-search"
        >搜索</el-button>
        <el-button
          type="success"
          @click="add"
          icon="el-icon-edit"
        >新增管理员</el-button>
      </el-form>
    </div>
    <el-table
      :data="userTable"
      border
      style="width: 100%"
    >
      <el-table-column
        label="序号"
        type="index"
        width="55"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="account"
        label="账号"
        width="180"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="nickname"
        label="姓名"
        width="180"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="organizations"
        label="所属支部"
        width="300"
      >
        <template slot-scope="{ row }">
          <el-tag
            v-for="(item,index) in row.organizations"
            :key="index"
            size="small"
            type="primary"
          >{{item.name}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="roles"
        label="角色"
        align="center"
        width="150"
      >
        <template slot-scope="{ row }">
          <el-tag
            v-for="(item,index) in row.roles"
            :key="index"
            size="small"
            type="primary"
          >{{item}}</el-tag>

        </template>
      </el-table-column>
      <el-table-column
        prop="status"
        label="状态"
        align="center"
        width="150"
      >
        <template slot-scope="{ row }">
          <el-tag
            size="small"
            type="success"
            v-if="row.status == 1"
          >正常</el-tag>
          <el-tag
            size="small"
            type="danger"
            v-else
          >禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop=""
        label="操作"
        align="center"
      >
        <template slot-scope="{ row }">
          <el-button
            type="primary"
            plain
            size="mini"
            @click="getDetail(row.id)"
          >详情</el-button>
          <el-button
            type="success"
            plain
            size="mini"
            color="#e97993"
            @click="editAdmin(row)"
            v-if="row.is_admin == 1"
          >编辑</el-button>
          <el-button
            :type="row.is_admin == 1 ? 'warning' : 'success'"
            plain
            size="mini"
            @click="userPwd(row)"
          >修改密码</el-button>
          <el-button
            type="warning"
            plain
            size="mini"
            v-if="row.is_admin == 0"
            @click="userRole(row)"
          >修改角色</el-button>
          <el-button
            type="danger"
            plain
            size="mini"
            v-if="row.is_admin == 1"
            @click="deleteUser(row.id)"
          >删除管理员</el-button>
          <el-button
            type="danger"
            plain
            size="mini"
            v-else
            @click="stopUser(row)"
          >禁用</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <div class="paging">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="searchParams.page"
        background
        :page-sizes="[15, 20, 30, 50, 100, 200]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalPage"
      >
      </el-pagination>
    </div>
    <!--新增管理员-->
    <el-dialog
      title="新增管理员"
      :visible.sync="dialogVisible"
      width="50%"
      center
    >
      <el-form
        :model="creatForm"
        :rules="rules"
        ref="creatForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item
          label="姓名"
          prop="name"
        >
          <el-input v-model="creatForm.name"></el-input>
        </el-form-item>
        <el-form-item
          label="账号"
          prop="account"
        >
          <el-input v-model="creatForm.account"></el-input>
        </el-form-item>
        <el-form-item
          label="密码"
          prop="password"
        >
          <el-input v-model="creatForm.password"></el-input>
        </el-form-item>
          <div class="position">
        <span class="xing">*</span>
        <el-form-item
          label="所属支部"
          prop="organization_ids"
        >
         
          <el-select
            multiple
            v-model="organizationIds"
            @change="selectOrg"
            ref='select'
            remote
            reserve-keyword
            placeholder="请输入关键词"
            
          >
            <el-option
              v-for="item in treeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
          </div>
        <el-form-item
          label="状态"
          prop="status"
        >
          <el-select
            v-model="creatForm.status"
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="item in status"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="角色"
          prop="role"
        >
          <el-radio-group
            v-for="(item, index) in roles"
            :key="index"
            v-model="creatForm.role"
          >
            <el-radio
              :label="index"
              style="margin-right:20px;"
            >{{
              item
              }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="cancelCreated">取 消</el-button>
        <el-button
          type="primary"
          @click="createUsers('creatForm')"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!--编辑管理员信息-->
    <el-dialog
      title="编辑管理员"
      :visible.sync="editDialogVisible"
      width="50%"
      center
    >
      <el-form
        :model="creatForm"
        :rules="rules"
        ref="creatForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item
          label="姓名"
          prop="name"
        >
          <el-input v-model="creatForm.name"></el-input>
        </el-form-item>
        <el-form-item
          label="账号"
          prop="account"
        >
          <el-input v-model="creatForm.account"></el-input>
        </el-form-item>
        </el-form-item>
        <div class="position">
        <span class="xing">*</span>
        <el-form-item
          label="支部"
          prop="organization_ids"
        >
          <el-select
            v-model="creatForm.organization_ids"
            clearable

            @change="selectOrganiz"
            placeholder="所属支部"
          >
            <el-option
              v-for="item in treeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        </div>
        <el-form-item
          label="角色"
          prop="role"
        >
          <el-radio-group
            v-for="(item, index) in roles"
            :key="index"
            v-model="creatForm.role"
          >
            <el-radio
              :label="index"
              style="margin-right:20px;"
            >{{
              item
              }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="putUsers('creatForm')"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!--修改用户密码和身份-->
    <el-dialog
      :title="type == 0 ? '修改密码' : '修改角色'"
      :visible.sync="passwordVisible"
      width="50%"
      center
    >
      <el-form
        :model="editPassword"
        :rules="rules"
        ref="editPassword"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item
          label="姓名"
          prop="name"
        >
          <el-input v-model="editPassword.name"></el-input>
        </el-form-item>
        <el-form-item
          label="账号"
          prop="account"
        >
          <el-input v-model="editPassword.account"></el-input>
        </el-form-item>
        <el-form-item
          v-if="type == 0"
          label="密码"
          prop="password"
        >
          <el-input v-model="editPassword.password"></el-input>
        </el-form-item>
        <el-form-item
          v-else
          label="角色"
          prop="role"
        >
          <el-radio-group
            v-for="(item, index) in roles"
            :key="index"
            v-model="editPassword.role"
          >
            <el-radio
              :label="index"
              style="margin-right:20px;"
            >{{item}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="passwordVisible = false">取 消</el-button>
        <el-button
          type="primary"
          v-if="type == 0"
          @click="surePwd('creatForm')"
        >确 定</el-button>
        <el-button
          type="primary"
          v-else
          @click="sureRole('creatForm')"
        >确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="详情"
      :visible.sync="detailVisible"
      width="30%"
      center
    >
      <div class="detail">
        <div>账号：{{ detailList.account }}</div>
        <div>昵称：{{ detailList.nickname }}</div>
        <div>身份：{{ detailList.is_admin_text }}</div>
        <div v-if="detailList.staff">
          <div>姓名：{{ detailList.staff.true_name }}</div>
          <div>学号：{{ detailList.staff.no }}</div>
          <div>班级：{{ detailList.staff.class }}</div>
        </div>
      </div>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="detailVisible = false"
        >关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  usersLists,
  addUsers,
  deleteUsers,
  putUsers,
  changeUserPwd,
  changeUserRole,
  usersDetail
} from "@/api/administrator/index";
import { fatherLists } from "@/api/organizationList/index";

export default {
  data() {
    return {
      loadingFull: false,
      dialogVisible: false,
      editDialogVisible: false,
      passwordVisible: false, //修改
      detailVisible: false,
      detailList: "",
      userTable: [],
      type: "",
      creatForm: {
        name: "",
        account: "",
        status: 1,
        password: "",
        organization_ids: "",
        role: "2"
      },
      editPassword: {
        name: "",
        account: "",
        password: ""
      },
      organizationIds: "",
      roles: [],
      status: [
        {
          value: 0,
          name: "暂停"
        },
        {
          value: 1,
          name: "正常"
        }
      ],
      searchParams: {
        name: "",
        account: "",
        status: 1,
        is_admin: 1,
        limit: 15, //每页显示条数
        page: 1 //当前页码
      }, //搜索框数据
      totalPage: 0, //总页码
      isAdmin: [
        {
          value: 0,
          label: "学生"
        },
        {
          value: 1,
          label: "管理员"
        },
        {
          value: 2,
          label: "超级管理员"
        }
      ],
      treeList: [
        {
          pid: 0,
          id: 0,
          name: "未选择"
        }
      ], //支部列表
      rules: {
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        account: [{ required: true, message: "请输入账号", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
          status: [{ required: true, message: "请选择状态", trigger: "change" }],
        role: [{ required: true, message: "请选择角色", trigger: "change" }]
      }
    };
  },

  created() {
    this.usersLists(this.searchParams);
    let allStatus = JSON.parse(sessionStorage.getItem("status"));
    this.roles = { 2: "管理员", 3: "超级管理员" };
    //获取父级组织列表
    fatherLists().then(res => {
      console.log(res, "llllll");
      this.treeList = res.data;
      console.log("opopop");
    });
  },
  methods: {
    //  close() {
    //     this.$refs['creatForm'].resetFields()
    //     // this.form = this.$options.data().form
    //     this.editDialogVisible = false
    //   },
    add(){
      this.dialogVisible = true
     
    },

    searchList() {
      this.usersLists(this.searchParams);
    },
    //选择支部
    selectOrg(){
      this.creatForm.organization_ids=this.organizationIds
      console.log(this.organizationIds,'organizationIds')
      console.log(this.creatForm.organization_ids,'organizationIds')

      this.$refs.select.blur()
    },
    //管理员列表
    async usersLists(params) {
      this.loadingFull = true;
      await usersLists(params)
        .then(res => {
          console.log(res, "人员列表");
          this.userTable = res.data.data;
          this.loadingFull = false;
          this.totalPage = res.data.meta.pagination.total;
        })
        .catch(err => {
          this.loadingFull = false;
        });
    },
    //查看详情
    getDetail(id) {
      this.loadingFull = true;
      usersDetail(id)
        .then(res => {
          this.detailList = res.data;
          this.detailVisible = true;
          this.loadingFull = false;
        })
        .catch(err => {
          this.loadingFull = false;
        });
    },

    async createUsers(formName) {
      //this.creatForm.organization_ids = this.organizationIds;
      console.log(this.creatForm.organization_ids, "crest");

      if(!this.creatForm.organization_ids){
         this.$message.error("请选择支部");
         return;
      }
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.addUsers();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //新增管理员
    async addUsers() {
      await addUsers(this.creatForm)
        .then(res => {
          console.log(res, "新增");
          this.$message.success("新增成功");
          this.dialogVisible = false;
          this.usersLists(this.searchParams);
        })
        .catch(err => {
          this.loadingFull = false;
        });
    },
//取消新增管理员
cancelCreated(){
  this.dialogVisible=false
  this.organizationIds=[]
  this.$refs.creatForm.resetFields()
},
    //删除管理员
    deleteUser(id) {
      this.$confirm("此操作将删除管理员账号, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          deleteUsers(id).then(res => {
            if (res.code == 200) {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              this.usersLists(this.searchParams);
            } else {
              this.$message({
                type: "error",
                message: "删除失败!"
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    async putUsers() {
      await putUsers(this.creatForm)
        .then(res => {
          this.$message.success("修改成功");
          this.editDialogVisible = false;
          this.usersLists(this.searchParams);
        })
        .catch(err => {
          this.editDialogVisible = false;
        });
    },
    //禁用账号
    stopUser(row) {
      console.log(row, "pppppppppppppppppppppppppp");
      this.$confirm("此操作将禁用该账号, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          const data = {
            id: row.id,
            name: row.nickname,
            account: row.account,
            status: 0,
            role: 1,
            organization_ids: row.organization_ids
          };

          putUsers(data)
            .then(res => {
              this.$message({
                type: "success",
                message: "禁用成功!"
              });
              this.usersLists(this.searchParams);
            })
            .catch(err => {
              this.$message({
                type: "error",
                message: "禁用失败!"
              });
              this.usersLists(this.searchParams);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //编辑管理员信息
    editAdmin(row) {
      let arr=[]
    this.organizationIds = arr.push(Number(row.organization_ids[0])),

    console.log(this.organizationIds,'PPPPPPPPPPPPPPPPPPPPPPPPPP')
      this.editDialogVisible = true;
      this.creatForm = {
        name: row.nickname,
        id: row.id,
        account: row.account,
        status: 1,
        password: row.password,
        organization_ids:[this.organizationIds],
        role: "2"
      };
    },
    //选择支部
    selectOrganiz(item) {
      console.log(item);
      let arr = [];
      arr.push(item);
      this.creatForm.organization_ids = arr;
      //  this.$refs.selectblur.blur()
    },
    //修改密码
    userPwd(row) {
      this.passwordVisible = true;
      this.type = 0;
      this.editPassword = {
        id: row.id,
        name: row.nickname,
        account: row.account,
        password: ""
      };
    },
    //修改用户角色
    userRole(row) {
      this.passwordVisible = true;
      this.type = 1;
      this.editPassword = {
        id: row.id,
        name: row.nickname,
        account: row.account,
        role: ""
      };
      if (row.is_admin == 0) {
        this.roles = { 1: "用户", 2: "管理员", 3: "超级管理员" };

        this.editPassword.role = "1";
      } else {
        this.editPassword.role = "2";
      }
    },
    sureRole() {
      changeUserRole(this.editPassword)
        .then(res => {
          this.$message({
            type: "success",
            message: "身份修改成功"
          });
          this.usersLists(this.searchParams);
          this.passwordVisible = false;
        })
        .catch(err => {
          this.$message({
            type: "error",
            message: "修改失败"
          });
          this.passwordVisible = false;
        });
    },
    surePwd() {
      changeUserPwd(this.editPassword)
        .then(res => {
          this.$message({
            type: "success",
            message: "密码修改成功"
          });
          this.usersLists(this.searchParams);
          this.passwordVisible = false;
        })
        .catch(err => {
          this.$message({
            type: "error",
            message: "修改失败"
          });
          this.passwordVisible = false;
        });
    },
    //切换页码
    handleSizeChange(e) {
      console.log(e, "切换页码");
      this.searchParams.limit = e;
      const data = this.searchParams;
      this.usersLists(data);
    },
    //切换每页显示数量
    handleCurrentChange(e) {
      console.log(e, "当前页码");
      this.searchParams.page = e;
      const data = this.searchParams;
      this.usersLists(data);
    }
  }
};
</script>
<style lang="scss" scoped>
@import "@/assets/styles/content.scss";

.demo-ruleForm {
  width: 50%;
  margin: 0 auto;
}
::v-deep .el-dialog .el-dialog__body{
      display: flex;
      justify-content: center;
      align-items: center;
}
.position{
  position: relative;
  .xing{
position: absolute;
color: red;
top: 15px;
    left: 20px;
  }
}
.detail {
  width: 80%;
  margin: 0 auto;
  padding-bottom: 30px;
  div {
    height: 30px;
    line-height: 30px;
  }
}
</style>
