<template>
  <div class="lsadmin-container">
    <el-tabs v-model="activeName" type="border-card">
      <el-tab-pane label="账号列表" name="1">
        <el-form :inline="true" :model="searchParam" class="demo-form-inline">
          <el-form-item label="关键字">
            <el-input clearable v-model="searchParam.realname" size="small" placeholder="模糊匹配用户名和姓名"/>
          </el-form-item>
          <el-form-item label="角色">
            <el-select filterable clearable v-model="searchParam.authGroup" size="small" placeholder="-请选择-">
              <el-option v-for="(item,index) in roleList" :key="index" :label="item.name" :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="区划">
            <driverAreaSelect v-model="searchParam.driverArea"></driverAreaSelect>
          </el-form-item>
          <el-form-item>
            <el-button :loading="tableLoading" @click="search" size="small" icon="el-icon-search" type="primary">搜索
            </el-button>
            <el-button @click="initSearchParam();search()" icon="el-icon-refresh-right"
                       type="primary" size="small"
                       style="background-color: #fff; border: 1px solid #ccc ; color: #666">清空
            </el-button>
          </el-form-item>
        </el-form>
        <el-table stripe ref="table" :height="tableHeight" v-loading="tableLoading"
                  :data="dataList"
                  size="medium"
                  border>
          <el-table-column :index="indexMethod" label="序号" type="index" width="80" align="center"/>
          <el-table-column show-overflow-tooltip prop="realname" label="姓名" align="center"/>
          <el-table-column show-overflow-tooltip prop="username" label="用户名" align="center" min-width="80"/>
          <el-table-column show-overflow-tooltip prop="authGroupName" label="角色" align="center" min-width="100"/>
          <el-table-column show-overflow-tooltip prop="driverAreaName" label="区划" align="center" min-width="120"/>
          <el-table-column show-overflow-tooltip prop="status" label="状态" min-width="100" align="center">
            <template slot-scope="{row}">
              <el-switch v-if="isAdmin||btnRule.some(btn=>btn=='status')" v-model="row.status" :active-value="1"
                         :inactive-value="2" size="small"
                         @change="changeStatus(row)"/>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="lastTime" min-width="150" label="最近登陆时间" align="center"/>
          <el-table-column v-if="isAdmin||btnRule.some(btn=>btn=='edit'||btn=='info'||btn=='resetPwd')" width="160" label="操作" align="center">
            <template slot-scope="scoped">
              <el-tooltip v-if="isAdmin||btnRule.some(btn=>btn=='info')" class="item" effect="dark" content="详情"
                          placement="bottom">
                <el-button @click="handleEdit(scoped.row,1)" type="primary" size="mini" icon="el-icon-tickets"/>
              </el-tooltip>
              <el-tooltip v-if="isAdmin||btnRule.some(btn=>btn=='edit')" class="item" effect="dark" content="编辑"
                          placement="bottom">
                <el-button @click="handleEdit(scoped.row)" type="primary" size="mini" icon="el-icon-edit"/>
              </el-tooltip>
              <el-button v-if="isAdmin||btnRule.some(btn=>btn=='resetPwd')" @click="resetPwd(scoped.row)" type="primary" size="mini">重置密码</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div  class="page-current">
          <el-pagination
            background
            :current-page="currentPage"
            :page-size="pageSize"
            prev-text="上一页"
            next-text="下一页"
            layout="total, prev, pager, next, jumper"
            style="display: inline-block;"
            @current-change="handleCurrentChange"
            :total="count"/>
        </div>
      </el-tab-pane>
      <el-tab-pane v-if="isAdmin||btnRule.some(btn=>btn=='add')" label="添加人员" name="2">
        <laadminForm :levelList="levelList" :roleList="roleList"  :ruleForm="ruleForm"
                    style="width: 50%" v-if="activeName==2" @submit="submit"></laadminForm>
      </el-tab-pane>
    </el-tabs>
    <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" center :visible.sync="addDialogVisible" :title="ruleForm.disabled?'人员详情':'修改人员'">
      <laadminForm :levelList="levelList" :roleList="roleList" v-if="addDialogVisible" ref="dialogForm" :ruleForm="ruleForm"
                  style="width: 100%" @submit="submit" @onBack="onBack"></laadminForm>
    </el-dialog>
  </div>
</template>

<script>
  import lsauthgroupApi from '@/api/system/lsauthgroup'
  import lsadminApi from '@/api/system/lsadmin'
  import laadminForm from './edit'
  import driverAreaSelect from '@/components/driverAreaSelect'
  import {mapGetters} from "vuex";

  export default {
    name: "lsadmin",
    data() {
      return {
        roleList:[],
        activeName: '1',
        searchParam: {
          realname:'',
          authGroup:'',
          driverArea:''
        },
        addDialogVisible: false,
        ruleForm: {
          realname: '',
          username: '',
          authGroup:[],
          level:'',
          gender: '',
          duty: '',
          mobile: '',
          email:'',
          driverArea: '',
          note:''
        },
        levelList:{},
        currentPage: 1,
        pageSize: parseInt((document.body.clientHeight - 290 - 43) / 44.5),
        count: 0,
        dataList: [],
        tableLoading: false,
        tableHeight: document.body.clientHeight - 290
      }
    },
    components: {laadminForm,driverAreaSelect},
    computed: {
      ...mapGetters(["btnRule", "isAdmin"])
    },
    created() {
    },
    mounted() {
      this.tableLoading = true
      this.getAuthGroupList()
      this.getAllList()
      this.getBaseData()
    },
    watch: {
      activeName() {
        this.initRuleForm()
      }
    },
    methods: {
      // 图片加载失败处理
      errorHandler() {
        return true
      },
      // 异步获取数据
      async queryData(){
        // 获取角色
        await this.getAuthGroupList()
      },
      // 初始化搜索条件
      initSearchParam() {
        this.searchParam = {
          realname: '',
          driverArea:'',
        }
      },
      // 获取数据列表
      getLsadminList() {
        let searchParam = JSON.parse(JSON.stringify(this.searchParam))
        searchParam.pageIndex = this.currentPage
        searchParam.pageSize = this.pageSize
        adminApi.lsadminList(searchParam).then(res => {
          this.lsadminList = res.data.records
          this.count = res.data.total
          this.tableLoading = false
        }).catch(e => {
          this.lsadminList = []
          this.tableLoading = false
        })
      },
      // 获取编辑数据
      adminInfo(data){
        // 初始化表单
        this.initInfoForm()
        // 显示弹窗
        this.addDialogVisible=true
        // 设置标题
        if (data == null) {
          this.dialogTitle = "添加";
        } else {
        this.dialogTitle = "编辑";
        }
        this.$nextTick(function () {
          try {
            adminApi.lsadminInfo({id: data.id}).then(res => {
              let infoForm = JSON.parse(JSON.stringify(res.data))
              if (!infoForm.authGroup) {
                infoForm.authGroup = []
              } else {
                infoForm.authGroup = infoForm.authGroup.split(',')
              }
              this.infoForm = Object.assign({}, infoForm)
              this.$refs.editForm.$refs['infoForm'].resetFields()
            }).catch(e => {
            })
          } catch (e) {

          }
        })
      },
      // 初始化表单
      initInfoForm() {
        this.infoForm = {
          realname: '',
          gender: 1,
          status: 1,
          sort: 125,
          authGroup: [],
        }
      },
      // 重置密码
      resetPwd(data) {
        this.$confirm('确定要重置密码吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.tableLoading = true
          lsadminApi.resetPwd({id: data.id}).then(res => {
            this.tableLoading = false
            this.$message({
              type: 'success',
              message: '重置密码成功！'
            })
          }).catch(e => {
            this.tableLoading = false
          })
        })
      },
      // 设置状态
      changeStatus(data) {
        var content = ''
        if (data.status === 1) {
          content = '确定要启用吗？'
        } else {
          content = '确定要禁用吗？'
        }
        this.$confirm(content, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let params = {
            status: data.status == 1 ? '1' : '2',
            id: data.id
          }
          this.tableLoading = true
          lsadminApi.setStatus(params).then(res => {
            this.$message({
              type: 'success',
              message: '操作成功！'
            })
            this.getAllList()
          }).catch(e => {
            let dataList = JSON.parse(JSON.stringify(this.dataList))
            for (let i = 0; i < dataList.length; i++) {
              if (dataList[i].id == data.id) {
                dataList[i].status = data.status == 1 ? 2 : 1
              }
            }
            this.dataList = Object.assign([], dataList)
            this.tableLoading = false
          })
        }).catch(() => {
          let dataList = JSON.parse(JSON.stringify(this.dataList))
          for (let i = 0; i < dataList.length; i++) {
            if (dataList[i].id == data.id) {
              dataList[i].status = data.status == 1 ? 2 : 1
            }
          }
          this.dataList = Object.assign([], dataList)
        })
      },
      getAuthGroupList(){
        lsauthgroupApi.getAuthGroupList().then(res => {
          this.roleList=res.data?res.data:[]
        }).catch(e => {
          this.roleList=[]
        })
      },
      getBaseData(){
        lsadminApi.getBaseData().then(res => {
          const {level_list}=res.data
          this.levelList=level_list?level_list:{}
        }).catch(e => {
          this.levelList={}
        })
      },
      indexMethod(index) {
        return (index + 1) + ((this.currentPage - 1) * this.pageSize);
      },
      handleEdit(data, type) {
        this.initRuleForm()
        let child = JSON.parse(JSON.stringify(data))
        if (type) {
          child.disabled = true
        }
        if(child.authGroup){
          child.authGroup=child.authGroup.split(',')
        }else{
          child.authGroup=[]
        }
        this.ruleForm=Object.assign({},child)
        this.addDialogVisible = true
      },
      initRuleForm() {
        this.ruleForm = {
          realname: '',
          username: '',
          authGroup:[],
          level:'',
          gender: '',
          duty: '',
          mobile: '',
          email:'',
          driverArea: '',
          note:''
        }
      },
      getAllList() {
        let searchParam = JSON.parse(JSON.stringify(this.searchParam))
        searchParam.page = this.currentPage
        searchParam.pageSize = this.pageSize
        lsadminApi.lsadminList(searchParam).then(res => {
          const {total,records}=res.data
          this.count = total
          this.dataList = records?records:[]
          this.tableLoading = false
        }).catch(err => {
          this.dataList = []
          this.tableLoading = false
        })
      },
      search() {
        this.currentPage = 1
        this.tableLoading = true
        this.$refs.table.bodyWrapper.scrollTop = 0;
        this.getAllList()
      },
      handleCurrentChange(val) {
        this.currentPage = val
        this.tableLoading = true
        this.$refs.table.bodyWrapper.scrollTop = 0;
        this.getAllList()
      },
      initSearchParam() {
        this.searchParam = {
          realname:'',
          authGroup:'',
          driverArea:''
        }
      },
      submit(type) {
        if (type == 1) {
          this.activeName='1'
          this.search()
        } else {
          this.tableLoading = true
          this.getAllList()
          this.$refs.table.bodyWrapper.scrollTop = 0;
          this.addDialogVisible = false
        }
      },
      onBack() {
        this.initRuleForm()
        this.addDialogVisible = false
      }
    }
  }
</script>

<style lang="less">
  .lsadmin-container {
    width: 100%;

    .el-input.is-disabled .el-input__inner {
      background-color: #fff !important;
      color: #333 !important;
    }
  }
</style>
