<template>
  <div class="admin-container">
    <el-tabs v-model="activeName" type="border-card">
      <el-tab-pane label="账号列表" name="list">
        <el-form :inline="true" :model="searchParam" class="demo-form-inline head-form">
          <el-form-item label="关键词">
            <el-input clearable v-model="searchParam.keywords" size="small" placeholder="请输入用户名或姓名"
                      style="width: 200px"/>
          </el-form-item>
          <el-form-item label="公司名称">
            <el-input clearable v-model="searchParam.company" size="small" placeholder="请输入公司名称" style="width: 200px"/>
          </el-form-item>
          <el-form-item label="角色">
            <el-cascader
              size="small"
              placeholder="无"
              v-model="searchParam.authGroup"
              ref="refHandle"
              :options="roleList"
              :props="{ checkStrictly: true ,value:'id',label:'name'}"
              clearable></el-cascader>
          </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="adminList" border
                  row-key="id">
          <el-table-column show-overflow-tooltip prop="id" label="ID" align="center" width="100"/>
          <el-table-column show-overflow-tooltip prop="realname" label="姓名" align="center"/>
          <el-table-column show-overflow-tooltip prop="username" label="用户名" align="center"/>
          <el-table-column show-overflow-tooltip prop="company" label="公司名称" align="center"/>
          <el-table-column show-overflow-tooltip prop="authGroupText" label="角色" align="center"/>
          <el-table-column show-overflow-tooltip prop="cityName" label="区域数据权限" align="center"/>
          <el-table-column show-overflow-tooltip prop="status" label="状态" align="center" width="120">
            <template slot-scope="{row}">
              {{ row.status === 1 ? '正常' : '禁用' }}
              <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
            v-if="isAdmin||(btnRule.filter(value=>value=='edit'||value=='password'||value=='setPermit'||value=='view').length>0)"
            label="操作" width="220">
            <template slot-scope="scoped">
              <el-tooltip v-if="isAdmin||btnRule.some(btn=>btn=='edit')" class="item" effect="dark" content="编辑"
                          placement="bottom">
                <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleAddRole(scoped.row)"/>
              </el-tooltip>
              <el-tooltip v-if="isAdmin||btnRule.some(btn=>btn=='password')" class="item" effect="dark" content="重置密码"
                          placement="bottom">
                <el-button :loading="resetPasswordLoading" icon="el-icon-setting" type="primary" size="mini"
                           class="reset"
                           @click="resetPassword(scoped.row)">
                </el-button>
              </el-tooltip>
              <el-button v-if="isAdmin||btnRule.some(btn=>btn=='setPermit')" type="success" size="mini"
                         icon="el-icon-share" @click="limitDetail(scoped.row)">
                权限
              </el-button>
              <el-tooltip v-if="isAdmin||btnRule.some(btn=>btn=='view')" class="item" effect="dark" content="详情"
                          placement="bottom">
                <el-button type="primary" size="mini" icon="el-icon-document" class="detail"
                           @click="detail(scoped.row)">
                  详情
                </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <div class="page-current">
          <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            prev-text="上一页"
            next-text="下一页"
            background
            layout="total, prev, pager, next, jumper"
            style="display: inline-block;"
            :total="count"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-tab-pane>
      <el-tab-pane v-if="isAdmin||btnRule.some(btn=>btn=='add')" label="新增账号" name="add">
        <el-form ref="ruleForm" v-loading="loading" :model="ruleForm" size="small" label-width="100px"
                 style="width: 50%" class="form">
          <el-form-item label="姓名" prop="realname"
                        :rules="[{
                    required: true, message: '姓名不能为空', trigger: 'blur'
                  },
                {min: 2, max: 10, message: '长度在2 到 10 个字符', trigger: 'blur'}]">
            <el-input maxlength="10" clearable v-model="ruleForm.realname" size="small" placeholder="请输入姓名"/>
          </el-form-item>
          <el-form-item label="用户名" prop="username" :rules="[{
                    required: true, message: '用户名不能为空', trigger: 'blur'
                  },
                {min: 2, max: 20, message: '长度在2 到 20 个字符', trigger: 'blur'}]">
            <el-input maxlength="20" clearable v-model="ruleForm.username" size="small" placeholder="请输入用户名"/>
          </el-form-item>
          <el-form-item label="职务" prop="duty" :rules="[
                {min: 0, max: 10, message: '不能超过10 个字符', trigger: 'blur'}]">
            <el-input maxlength="10" clearable v-model="ruleForm.duty" size="small" placeholder="请输入职务"/>
          </el-form-item>
          <el-form-item label="公司" prop="company" :rules="[{
                    required: true, message: '公司不能为空', trigger: 'blur'
                  },
                {min: 2, max: 20, message: '长度在2 到 20 个字符', trigger: 'blur'}]">
            <el-input maxlength="20" clearable v-model="ruleForm.company" size="small" placeholder="请输入公司名"/>
          </el-form-item>
          <el-form-item label="手机" prop="mobile" :rules="[
                    {required: true,validator: validatePhone, trigger: 'blur'}
                    ]">
            <el-input maxlength="11" clearable v-model="ruleForm.mobile" size="small" placeholder="请输入手机号"/>
          </el-form-item>
          <el-form-item label="角色" prop="authGroup">
            <el-cascader
              placeholder="无"
              v-model="ruleForm.authGroup"
              ref="refHandle"
              :options="roleList"
              :props="{ checkStrictly: true ,value:'id',label:'name'}"
              clearable></el-cascader>
          </el-form-item>
          <el-form-item label="区属权限" prop="cityIds">
            <el-checkbox-group v-model="ruleForm.cityIds">
              <el-checkbox v-for="city in cityList" :label="city.id" :key="city.id">{{city.name}}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-document-add" :loading="addBtnLoading" type="primary" size="small"
                       @click="submitForm('ruleForm',1)">立即提交
            </el-button>
            <el-button icon="el-icon-back" size="small" class="back" @click="resetForm('ruleForm')">返回</el-button>
          </el-form-item>

        </el-form>
      </el-tab-pane>
    </el-tabs>
    <!-- 编辑角色 -->
      <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" center :visible.sync="addDialogVisible"
                 :title="dialogType==='edit'? '编辑' : '详情'">
        <el-form ref="ruleForm" v-loading="loading" :model="ruleForm" size="small" label-width="100px"
                 class="form">
          <el-form-item label="姓名" prop="realname"
                        :rules="[{
                    required: true, message: '姓名不能为空', trigger: 'blur'
                  },
                {min: 2, max: 10, message: '长度在2 到 10 个字符', trigger: 'blur'}]">
            <el-input maxlength="10" clearable :disabled="dialogType=='detail'?true:false" v-model="ruleForm.realname"
                      size="small" placeholder="请输入姓名"/>
          </el-form-item>
          <el-form-item label="用户名" prop="username" :rules="[{
                    required: true, message: '用户名不能为空', trigger: 'blur'
                  },
                {min: 2, max: 20, message: '长度在2 到 20 个字符', trigger: 'blur'}]">
            <el-input maxlength="20" clearable :disabled="dialogType=='detail'?true:false" v-model="ruleForm.username"
                      size="small" placeholder="请输入用户名"/>
          </el-form-item>
          <el-form-item label="职务" prop="duty" :rules="[
                {min: 0, max: 10, message: '不能超过10 个字符', trigger: 'blur'}]">
            <el-input maxlength="10" clearable :disabled="dialogType=='detail'?true:false" v-model="ruleForm.duty"
                      size="small" placeholder="请输入职务"/>
          </el-form-item>
          <el-form-item label="公司" prop="company" :rules="[{
                    required: true, message: '公司不能为空', trigger: 'blur'
                  },
                {min: 2, max: 20, message: '长度在2 到 20 个字符', trigger: 'blur'}]">
            <el-input maxlength="20" clearable :disabled="dialogType=='detail'?true:false" v-model="ruleForm.company"
                      size="small" placeholder="请输入公司名"/>
          </el-form-item>
          <el-form-item label="手机" prop="mobile" :rules="[
                    {required: true,validator: validatePhone, trigger: 'blur'}
                    ]">
            <el-input maxlength="11" clearable :disabled="dialogType=='detail'?true:false" v-model="ruleForm.mobile"
                      size="small" placeholder="请输入手机号"/>
          </el-form-item>
          <el-form-item label="角色" prop="authGroup">
            <el-cascader
              :disabled="dialogType=='detail'?true:false"
              placeholder="无"
              v-model="ruleForm.authGroup"
              ref="refHandle"
              :options="roleList"
              :props="{ checkStrictly: true ,value:'id',label:'name'}"
              clearable></el-cascader>
          </el-form-item>
          <el-form-item label="区属权限" prop="cityIds">
            <el-checkbox-group :disabled="dialogType=='detail'?true:false" v-model="ruleForm.cityIds">
              <el-checkbox v-for="city in cityList" :label="city.id+''" :key="city.id">{{city.name}}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
                      <el-button icon="el-icon-document-add" v-if="dialogType=='edit'" :loading="addBtnLoading"
                                 type="primary" size="medium"
                                 @click="submitForm('ruleForm',2)">提交
            </el-button>
            <el-button icon="el-icon-back" size="medium" class="back"
                       @click="resetForm('ruleForm') ;addDialogVisible = false">返回</el-button>
        </span>
      </el-dialog>
    <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" center v-loading="treeLoading"
               class="menu-dialog" :visible.sync="menuVisible" title="设置权限">
      <el-tree
        ref="tree"
        :data="menuList"
        highlight-current
        check-strictly
        show-checkbox
        default-expand-all
        node-key="id"
        @check-change="handleCheckChange"
        :props="defaultProps">
      </el-tree>
      <span slot="footer" class="dialog-footer">
          <el-button icon="el-icon-document-add" size="medium" :loading="roleMenuLoading" type="primary"
                     @click="roleMenuSubmit">提交</el-button>
          <el-button icon="el-icon-back" size="medium" @click="menuVisible = false;initRuleForm()">取 消</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
  import roleApi from '@/api/permission/authRule'
  import menuApi from '@/api/permission/menu'
  import adminApi from '@/api/permission/admin'

  export default {
    name: "admin",
    data() {
      var phoneReg = /^1\d{10}$/
      var validatePhone = (rule, value, callback) => {
        if (value) {
          if (!phoneReg.test(value)) {
            callback(new Error('请输入正确手机号码'));
          } else {
            callback();
          }
        } else {
          callback(new Error('手机号码必填'));
        }
      };
      return {
        // 当前页
        validatePhone: validatePhone,
        currentPage: 1,
        // 总条数
        count: 0,
        // 每页条数
        pageSize: 10,
        roleList: [],
        addBtnLoading: false,
        menuVisible: false,
        tableLoading: false,
        resetPasswordLoading: false,
        roleMenuLoading: false,
        // 显示编辑角色弹框
        addDialogVisible: false,
        dialogType: 'new',
        treeLoading: false,
        // 用户按钮权限
        btnRoles: [],
        menuList: [],
        token: '',
        activeName: 'list',
        searchParam: {
          keywords: '',
          company: '',
          authGroup: ''
        },
        cityList: [],
        adminList: [],
        defaultProps: {
          children: 'children',
          label: 'title'
        },
        // 编辑/新增，表单
        ruleForm: {
          realname: '',
          username: '',
          duty: '',
          mobile: '',
          authGroup: '',
          company: '',
          cityIds: [],
          checkedKeys: []
        },
        options: [],
        isTreeBl: false,
        // 角色列表
        roles: [],
        loading: false,
        tableHeight: document.body.clientHeight - 290,
        btnRule: [],
        isAdmin: false
      }
    },
    created() {
      const {btnRule, isAdmin} = this.$store.state.user
      this.btnRule = btnRule
      this.isAdmin = isAdmin
      this.pageSize = parseInt((document.body.clientHeight - 344) / 50)
    },
    watch: {
      activeName() {
        this.initRuleForm()
      }
    },
    mounted() {
      this.tableLoading = true
      let me = this
      this.getRollList()
      this.getCityList(function () {
        me.getAllList()
      })
    },
    methods: {
      getRollList() {
        roleApi.roleList().then(res => {
          let roleList = res.data ? res.data : []
          this.roleList = roleList.filter(item => item.status == 1)
        }).catch(e => {
          this.roleList = []
        })
      },
      getCityList(call) {
        adminApi.getCityList().then(res => {
          this.cityList = res.data ? res.data : []
          call()
        }).catch(e => {
          this.cityList = []
          call()
        })
      },
      initRuleForm() {
        this.ruleForm = {
          realname: '',
          username: '',
          duty: '',
          mobile: '',
          authGroup: '',
          company: '',
          cityIds: []
        }
      },
      initSearchParam() {
        this.searchParam = {
          keywords: '',
          company: '',
          authGroup: ''
        }
      },
      handleCurrentChange(val) {
        this.tableLoading = true
        this.currentPage = val
        this.$refs.table.bodyWrapper.scrollTop = 0;
        this.getAllList()
      },
      search() {
        this.currentPage = 1
        this.tableLoading = true
        this.$refs.table.bodyWrapper.scrollTop = 0;
        this.getAllList()
      },
      handleCheckChange(data, checked, indeterminate) {
        if (!this.isTreeBl) {
          if (checked) {
            if (!this.checkedKeys.some(key => key == data.id)) {
              this.checkedKeys.push(data.id)
            }
            this.childNode(data.children)
            this.parentNode(data.pid)
          } else {
            for (let i = 0; i < this.checkedKeys.length; i++) {
              if (data.id == this.checkedKeys[i]) {
                this.checkedKeys.splice(i, 1)
                break
              }
            }
            this.childNode(data.children, 1)
          }
          this.isTreeBl = true
          this.$refs.tree.setCheckedKeys(this.checkedKeys);
          let me = this
          this.$nextTick(function () {
            me.isTreeBl = false
          })
        }
      },
      childNode(childList, type) {
        if (childList && childList.length > 0) {
          childList.map(item => {
            if (type) {
              for (let i = 0; i < this.checkedKeys.length; i++) {
                if (item.id == this.checkedKeys[i]) {
                  this.checkedKeys.splice(i, 1)
                  break
                }
              }
            } else {
              if (!this.checkedKeys.some(key => key == item.id)) {
                this.checkedKeys.push(item.id)
              }
            }
            this.childNode(item.children, type)
          })
        }
      },
      parentNode(pid, type) {
        if (pid) {
          this.findChild(this.menuList, pid, type)
        }
      },
      findChild(childList, pid, type) {
        let child = childList.find(item => item.id == pid)
        if (child) {
          if (!this.checkedKeys.some(key => key == child.id)) {
            this.checkedKeys.push(child.id)
            if (child.pid) {
              this.findChild(this.menuList, child.pid)
            }
          }
        } else {
          childList.map(item => {
            if (item.children && item.children.length > 0) {
              this.findChild(item.children, pid)
            }
          })
        }
      },
      roleMenuSubmit() {
        this.roleMenuLoading = true
        adminApi.setPermit({
          id: this.ruleForm.id,
          rules: this.checkedKeys.length > 0 ? this.checkedKeys.join(',') : ''
        }).then(res => {
          this.menuVisible = false
          this.$message({
            type: 'success',
            message: '权限保存成功！'
          })
          this.roleMenuLoading = false
          this.tableLoading = true
          this.getAllList()
        }).catch(e => {
          this.roleMenuLoading = false
        })
      },
      // 获取列表
      getAllList() {
        let searchParam = JSON.parse(JSON.stringify(this.searchParam))
        if (searchParam.authGroup) {
          if (Array.isArray(searchParam.authGroup) && searchParam.authGroup.length > 0) {
            searchParam.authGroup = searchParam.authGroup[searchParam.authGroup.length - 1]
          } else if (ruleForm.pid.length == 0) {
            searchParam.authGroup = ''
          }
        } else {
          if (!searchParam.authGroup) {
            searchParam.authGroup = ''
          }
        }
        searchParam.page = this.currentPage
        searchParam.pageSize = this.pageSize
        adminApi.accountList(searchParam).then(res => {
          let adminList = res.data.records ? res.data.records : []
          adminList.map(item => {
            if (item.cityIds) {
              let cityName = []
              let cityIds = item.cityIds.split(',')
              cityIds.map(id => {
                let item = this.cityList.find(child => child.id == id)
                if (item) {
                  cityName.push(item.name)
                }
              })
              item.cityName = cityName.join(',')
            } else {
              item.cityName = ''
            }
          })
          this.adminList = Object.assign([], adminList)
          this.count = res.data.total
          this.tableLoading = false
        }).catch(e => {
          this.adminList = []
          this.tableLoading = false
        })
      },
      // 新增角色
      handleAddRole(row) {
        this.dialogType = 'edit'
        let ruleForm = JSON.parse(JSON.stringify(row))
        if (ruleForm.authGroup) {
          ruleForm.authGroup = parseInt(ruleForm.authGroup)
        }
        if (!ruleForm.cityIds) {
          ruleForm.cityIds = []
        } else {
          ruleForm.cityIds = ruleForm.cityIds.split(',')
        }
        this.ruleForm = Object.assign({}, ruleForm)
        this.addDialogVisible = true
      },
      // 改变状态
      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 ? '2' : '1',
            id: data.id
          }
          this.tableLoading = true
          adminApi.accountEditStatus(params).then(res => {
            this.$message({
              type: 'success',
              message: '操作成功！'
            })
            this.getAllList()
          }).catch(e => {
            let adminList = JSON.parse(JSON.stringify(this.adminList))
            for (let i = 0; i < adminList.length; i++) {
              if (adminList[i].id == data.id) {
                adminList[i].status = data.status == 1 ? 2 : 1
              }
            }
            this.adminList = Object.assign([], adminList)
            this.tableLoading = false
          })
        }).catch(() => {
          let adminList = JSON.parse(JSON.stringify(this.adminList))
          for (let i = 0; i < adminList.length; i++) {
            if (adminList[i].id == data.id) {
              adminList[i].status = data.status == 1 ? 2 : 1
            }
          }
          this.adminList = Object.assign([], adminList)
          this.$message({
            type: 'info',
            message: '已取消该操作！'
          })
        })
      },
      // 重置密码
      resetPassword(data) {
        this.$confirm('确定要重置密码吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.resetPasswordLoading = true
          adminApi.accountReset({id: data.id}).then(res => {
            this.resetPasswordLoading = false
            this.$message({
              type: 'success',
              message: '重置密码成功！'
            })
          }).catch(e => {
            this.resetPasswordLoading = false
          })
        })
      },
      // 权限
      limitDetail(data) {
        this.menuVisible = true
        let me = this
        this.$nextTick(function () {
          me.checkedKeys = data.rules ? data.rules.split(',') : []
          me.$refs.tree.setCheckedKeys(me.checkedKeys);
          me.ruleForm = JSON.parse(JSON.stringify(data))
          if (me.menuList.length == 0) {
            me.queryMenuList()
          }
        })
      },
      queryMenuList() {
        menuApi.backMenuList({}).then(res => {
          this.menuList = res.data ? res.data : []
          this.treeLoading = false
        }).catch(e => {
          this.menuList = []
          this.treeLoading = false
        })
      },
      // 查看详情
      detail(row) {
        let ruleForm = JSON.parse(JSON.stringify(row))
        if (ruleForm.authGroup) {
          ruleForm.authGroup = parseInt(ruleForm.authGroup)
        }
        if (!ruleForm.cityIds) {
          ruleForm.cityIds = []
        } else {
          ruleForm.cityIds = ruleForm.cityIds.split(',')
        }
        this.ruleForm = Object.assign({}, ruleForm)
        this.dialogType = 'detail'
        this.addDialogVisible = true
      },
      // 提交按钮
      submitForm(formName, type) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let ruleForm = JSON.parse(JSON.stringify(this.ruleForm))
            if (ruleForm.authGroup) {
              if (Array.isArray(ruleForm.authGroup) && ruleForm.authGroup.length > 0) {
                ruleForm.authGroup = ruleForm.authGroup[ruleForm.authGroup.length - 1]
              } else if (ruleForm.authGroup.length == 0) {
                ruleForm.authGroup = ''
              }
            } else {
              if (!ruleForm.authGroup) {
                ruleForm.authGroup = ''
              }
            }
            if (ruleForm.cityIds.length > 0) {
              ruleForm.cityIds = ruleForm.cityIds.join(',')
            } else {
              ruleForm.cityIds = ''
            }
            this.addBtnLoading = true
            if (type == 1) {
              adminApi.accountAdd(ruleForm).then(res => {
                this.addBtnLoading = false
                this.initRuleForm()
                this.$refs[formName].resetFields()
                this.tableLoading = true
                this.$message({
                  type: 'success',
                  message: '添加成功！'
                })
                this.getAllList()
              }).catch(e => {
                this.addBtnLoading = false
              })
            } else {
              adminApi.accountEdit(ruleForm).then(res => {
                this.addBtnLoading = false
                this.initRuleForm()
                this.$refs[formName].resetFields()
                this.addDialogVisible = false
                this.tableLoading = true
                this.$message({
                  type: 'success',
                  message: '编辑成功！'
                })
                this.getAllList()
              }).catch(e => {
                this.addBtnLoading = false
              })
            }
          } else {
            return false
          }
        })
      },
      // 返回按钮
      resetForm(formName) {
        this.initRuleForm()
        this.$refs[formName].resetFields()
        this.activeName = 'list'
      }
    }
  }
</script>

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

    .menu-dialog {
      .el-dialog__body {
        padding: 10px 10px;
        height: 400px;
        overflow-y: auto;
      }
    }

    .el-input.is-disabled .el-input__inner {
      background-color: #fff;
      color: #333333;
    }

    .el-checkbox__input.is-disabled + span.el-checkbox__label {
      color: #333333;
    }

    .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner {
      background-color: #1890ff;
      border-color: #1890ff;
    }

    .head-form {
      width: 100% !important;
    }

    .page-current {
      text-align: center;
      padding: 15px 5px;
      padding-bottom: 0px;

      .sure-page-btn {
        display: inline-block;
        height: 28px;
        line-height: 0;
        width: 46px;
        padding: 0;
        vertical-align: top;
      }
    }
  }


</style>
