<template>
  <div class="main-contain">
    <div class="position">
      <bread-crumb :crumbs="crumbs"></bread-crumb>
     
       <div>
        <el-button
          type="primary"
          size="small"
          icon="el-icon-circle-plus-outline"
          style="float:left"
          @click="openForm(0)">新增</el-button>
        <el-button
        type="primary"
        size="small"
        @click="BatchDelete"
        >医药师登记</el-button>
     </div>
    
      
    </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"
        @selection-change="handleSelectionChange"
      > 
        <el-table-column
              align="center"
              type="selection"
              width="55">
        </el-table-column>  
        <el-table-column
          label="用户名"
          prop="user_name"
          min-width="160"
          align="center"
        ></el-table-column>
        <el-table-column label="医保医师编码" prop="doctor_number" min-width="160" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.doctor_number== 0"></span>
            <span v-if="scope.row.doctor_number!= 0">{{scope.row.doctor_number}}</span>
          </template>
        </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="状态" 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="240" 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>
            <span v-if="scope.row.user_type == 2">
              <el-button type="primary" size="small" icon="el-icon-refresh-left" @click="toReturn(scope.row.user_id,scope.row.is_mark)">
                    <span v-if="scope.row.is_mark ==0">登记</span>
                    <span v-if="scope.row.is_mark ==1">撤销</span>
              </el-button>
            </span>
          </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";
import axios from 'axios'
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,
      selectDrug:[]
    };
  },
  components: {
    BreadCrumb,
    AdminInfoForm
  },
  created: function() {
    this.local_user_id = this.$store.getters.xt_user.user.id;
    let page = 1;
    this.getRoles(page);
    adminMainView()
      .then(rs => {
        this.is_loading_admins = false;
        var resp = rs.data;
        if (resp.state === 1) {
           var adminData = resp.data.admins
           console.log("数据",adminData)
          this.admins.push(...adminData);
          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) {
             var admindata = resp.data.admins
          
            this.admins.push(...admindata);
            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);
    },
  //  toLogin(){
  //     var that = this
  //     axios.get('http://127.0.0.1:9532/sz/api/doctor/get').then(function(response) {
  //     if (response.data.state == 0) {
  //         that.$message.error(response.data.msg)
  //         return false
  //       } else {
  //         that.$message({ message: '登记成功', type: 'success' })
  //         }
  //        }).catch(function(error) {
  //     })
  //   },

   BatchDelete() {
      if (this.selectDrug.length == 0) {
        this.$message.error("请选择要登记的信息");
        return false;
      }
      this.$confirm(
        "确认要登记所选记录吗? <br>",
        "备案提示",
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(() => {
        var ids = [];
        var idMap = {};
        console.log("3333333",this.selectDrug)
        for (const index in this.selectDrug) {
          ids.push(this.selectDrug[index].user_id);
          idMap[this.selectDrug[index].user_id] = this.selectDrug[index].user_id;
        }
        
        var idss = ids.join(',')
        let params = {
          ids:idss,
          admin_user_id:this.$store.getters.xt_user.user.id
        }
        console.log("prams222",params)
        var that = this
        axios.get('http://127.0.0.1:9532/sz/api/doctor/get',{ params: params }).then(function(response) {
         if (response.data.state == 0) {
               that.$message.error(response.data.data.msg)
               return false
            } else {
              that.$message.error(response.data.data.msg)
              if(response.data.data.msg == ""){
                  that.$message.success("登记成功!")
                  that.adminMainView()
               }
               if(response.data.data.msg!=""){
                  that.$message.error(response.data.data.msg)
                  that.adminMainView()
               }
             }
           }).catch(function(error) {
        })
       });
     },
     toReturn(id,is_mark){
       var that = this
         let params = {
           'id':id,
           "is_mark":is_mark,
           "admin_user_id":this.$store.getters.xt_user.user.id
        }
        
         axios.get('http://127.0.0.1:9532/sz/api/medical/get',{params:params}).then(function(response) {
          if (response.data.state == 0) {
               that.$message.error(response.data.data.msg)
               return false
            } else {
             
              if(response.data.data.msg == ""){
                  that.$message.success("登记成功!")
                  that.adminMainView()
               }
               if(response.data.data.msg!=""){
                  that.$message.error(response.data.data.msg)
                  that.adminMainView()
               }
             }
           }).catch(function(error) {
        })
     },

   handleSelectionChange(val) {
      this.selectDrug = val;
    },
  },
  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>
