<template>
  <div class="full-size">
    <div class="main-header">
      <el-form inline :model="searchForm" @keyup.enter.native="search" @submit.native.prevent>
        <el-form-item>
          <el-input v-model.trim="searchForm.id" clearable placeholder="用户组登录名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model.trim="searchForm.displayName" clearable placeholder="显示名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="mini" @click="search" :disabled="loading">搜索</el-button>
        </el-form-item>
        <el-form-item class="right">
          <el-button v-permission="'group:CreateInstance'" @click.stop="toCreate" size="mini" icon="el-icon-plus" type="success">新建用户组</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="main-content">
      <div class="main-content-table-wrapper">
        <el-table ref="groupTable" :data="tableData" row-key="id" @row-click="tableCurrentChange" @selection-change="handleSelectionChange">
          <!--<el-table-column type="selection" width="45"></el-table-column>-->
          <el-table-column type="index" label="序号" width="50"></el-table-column>
          <el-table-column prop="id" :render-header="renderHeader" label="用户组名称" width="300"></el-table-column>
          <el-table-column prop="displayName" :render-header="renderHeader" label="显示名称" width="180"></el-table-column>
          <el-table-column prop="comments" label="备注"></el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
        </el-table>
      </div>
      <div class="main-content-page">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-size="pagination.pageSize" :page-sizes="$pagination.defaultPageSizes"
          :total="pagination.total"
          layout="prev, pager, next, total, sizes,  jumper"
          background>
        </el-pagination>
      </div>
    </div>

    <!--创建用户组-->
    <transition name="slide-fade-form-panel">
      <slide-form-panel v-if="createGroupFormShow">
        <div class="form-panel-title">
          <div class="form-panel-title-desc">
            <div class="form-panel-title-desc-text">新建用户组</div>
          </div>
          <div class="form-panel-title-close" @click="closeCreateGroupForm"><i class="el-icon-close"></i></div>
        </div>
        <div class="form-panel-content-wrapper">
            <el-form ref="createGroupForm"  label-width="100px" :model="groupForm"  :rules="groupFormRules" :inline-message="true">
              <el-form-item label="组名称：" prop="groupName">
                <el-input v-model.trim="groupForm.groupName" autocomplete='off'>
                  <template slot="suffix">
                    <span style="margin-top: 3px;">
                      @group.{{ tenantId}}
                    </span>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="显示名称：" prop="displayName">
                <el-input v-model="groupForm.displayName"></el-input>
              </el-form-item>
              <el-form-item label="备注：">
                <el-input
                  type="textarea"
                  :autosize="{ minRows: 3, maxRows: 5}"
                  placeholder=""
                  v-model="groupForm.comments">
                </el-input>
              </el-form-item>
            </el-form>
            <el-button type="primary" style="margin-top: 15px;" @click="createGroup" :disabled="saving">确定</el-button>
          </div>
      </slide-form-panel>
    </transition>

    <!--编辑用户组-->
    <transition name="slide-fade-form-panel">
      <slide-form-panel v-if="editGroupFormShow">
        <div class="form-panel-title">
          <div class="form-panel-title-desc">
            <div class="form-panel-title-desc-text">{{ groupForm.id }}</div>
            <div class="form-panel-title-desc-button">
              <div v-permission="'group:DeleteInstance'" class="plain-button" @click="toDeleteGroup(groupForm)">
                <i class="font_family icon-delete1 plain-button-icon"></i><span class="plain-button-text">删除</span>
              </div>
            </div>
          </div>
          <div class="form-panel-title-close" @click="closeEditGroupForm"><i class="el-icon-close"></i></div>
        </div>
        <div class="form-panel-content-wrapper" style="display: flex; flex-direction: column;">
          <el-form ref="groupForm"  label-width="100px" :model="groupForm"  :rules="groupFormRules" :inline-message="true">
            <el-form-item label="组名称：" readonly prop="groupName">
              <el-input v-model="groupForm.groupName"></el-input>
            </el-form-item>
            <el-form-item label="显示名称：" prop="displayName">
              <el-input v-model="groupForm.displayName"></el-input>
            </el-form-item>
            <el-form-item label="备注：">
              <el-input
                type="textarea"
                :autosize="{ minRows: 3, maxRows: 5}"
                placeholder=""
                v-model="groupForm.comments">
              </el-input>
            </el-form-item>
            <el-form-item v-permission="'user:ModifyInstanceAttribute'" label-width="100px">
              <el-button type="primary" @click="updateGroup">保存</el-button>
            </el-form-item>
          </el-form>
          <el-tabs style="margin: 10px 0px; flex: 1; border: 1px solid #E4E4E4;overflow: hidden;background: white; padding: 10px;" v-model="activeTabName">
            <el-tab-pane lazy label="组成员管理" name="user">
              <div class="full-size">
                <GroupUserSelector :groupId="groupForm.id"></GroupUserSelector>
              </div>
            </el-tab-pane>
            <el-tab-pane lazy label="权限管理" name="policy">
              <GroupPolicySelector :groupId="groupForm.id"></GroupPolicySelector>
            </el-tab-pane>
          </el-tabs>
        </div>
      </slide-form-panel>
    </transition>
  </div>
</template>

<script>
export default {
  name: 'Group',
  data () {
    const validateGroupname = (rule, value, callback) => {
      const reg = /^[A-Za-z0-9@_-]+$/
      if (!reg.test(value)) {
        callback(new Error('只能输入数字和字母!'))
      } else {
        callback()
      }
    }
    return {
      tenantId: this.$util.getTenantId(),
      createGroupFormShow: false,
      createGroupComplete: false,
      editGroupFormShow: false,
      isDisplayMoreSearch: true, // 是否显示更多搜索
      currentRow: null,
      nowSelectChangeRows: [],
      pagination: {
        currentPage: 1,
        pageSize: 20,
        total: 0
      },
      lastSearchForm: '',
      searchForm: {
        id: '',
        displayName: ''
      },
      currentTabName: 'create',
      customPassword: '134556',
      groupForm: {
        id: '',
        groupName: '',
        displayName: '',
        comments: ''
      },
      batchGroupForm: {
        password: '',
        repeatPassword: '',
        startAgentNo: '',
        endAgentNo: '',
        startExtNo: ''
      },
      groupFormRules: {
        displayName: [
          { required: true, message: '请输入显示名称' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符' }
        ],
        groupName: [
          { required: true, message: '请输入用户组名' },
          { pattern: /^[a-zA-Z]{1}[a-zA-Z\d_.-]{3,29}$/, message: '用户组名以字母开头，英文字母、数字、“.”、“_”或“-”， 4-30位' },
          { validator: validateGroupname, trigger: 'change' }
        ]
      },
      activeTabName: 'user',
      ruleForm: {},
      tableData: [],
      loading: false,
      saving: false,
      addData: {}
    }
  },
  computed: {
  },
  watch: {
    // GroupForm: {
    //   handler: function (newVal, oldVal) {
    //     if (this.permissions.update) {
    //       // 新建不需要及时保存，点击保存时再统一校验
    //       if (newVal.id) {
    //         this.updateGroup()
    //       }
    //     }
    //   },
    //   deep: true
    // }
  },
  mounted () {
    this.search()
  },
  methods: {
    handleSizeChange (val) {
      this.pagination.pageSize = val
      this.search()
      console.log(`每页 ${val} 条`)
    },
    handleCurrentChange (val) {
      this.pagination.currentPage = val
      this.search()
      console.log(`当前页: ${val}`)
    },
    search () {
      this.loading = true
      // 变更检索条件，设置到第一页
      const _lastSearchForm = this.$qs.stringify(this.searchForm)
      if (this.lastSearchForm !== _lastSearchForm) {
        this.pagination.currentPage = 1
      }
      this.lastSearchForm = _lastSearchForm

      this.$http.get(this.$apiUrl('listGroup') + `?page=${this.pagination.currentPage - 1}&size=${this.pagination.pageSize}&${_lastSearchForm}`)
        .then(response => {
          this.tableData = response.data.data
          console.log(this.tableData)
          // 重新设置总页数
          this.pagination.total = response.data.total
        })
        .catch((error) => {
          console.dir(error)
          this.$message.error(error.message)
        }).always(() => {
          this.loading = false
        })
    },
    toCreate () {
      this.resetForm()
      this.showCreateGroupForm()
    },
    updateGroup () {
      this.$refs.groupForm && this.$refs.groupForm.validate((valid) => {
        if (valid) {
          this.saving = true
          // 更新用户组
          this.$http.put(this.$apiUrl('systemGroup002', [this.groupForm.id]), this.$qs.stringify(this.groupForm))
            .then(response => {
              this.$message.success('修改成功')
              this.search()
            })
            .catch(error => {
              if (error.response) {
                this.$message.error(`修改失败! ${error.response.data.message}`)
              } else {
                this.$message.error(`修改失败! ${error.message}`)
              }
            })
            .always(() => {
              this.saving = false
            })
        } else {
          return false
        }
      })
    },
    // 创建用户组
    createGroup () {
      this.$refs.createGroupForm.validate((valid) => {
        if (valid) {
          this.saving = true
          this.$http.post(this.$apiUrl('createGroup'), this.groupForm)
            .then(response => {
              this.$message.success('创建成功')
              this.createGroupComplete = true
              this.groupForm.id = response.data.data.id
              this.showEditGroupForm()
              this.search()
            })
            .catch(error => {
              if (error.response) {
                this.$message.error(`创建失败! ${error.response.data.message}`)
              } else {
                this.$message.error(`创建失败! ${error.message}`)
              }
            })
            .always(() => {
              this.saving = false
            })
        }
      })
    },
    // 删除用户组
    toDeleteGroup (selection) {
      if (!selection.id && selection.length === 0) {
        this.$message.warning('请选择要删除的用户组')
      } else {
        this.$confirm('删除用户组将删除组成员，及授权权限策略, 是否确认?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deleteGroup(selection)
        })
      }
    },
    toDeleteGroups (selection) {
      if (!selection.id && selection.length === 0) {
        this.$message.warning('请选择要删除的用户组')
      } else {
        this.$confirm('此操作将永久删除用户组, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deleteGroup(selection)
        })
      }
    },
    deleteGroup (selection) {
      let _id = selection.id
      if (Array.isArray(selection)) {
        _id = selection.map(row => row.id).join(',')
      }
      this.$http.delete(this.$apiUrl('deleteGroup') + `?id=${_id}`)
        .then(response => {
          this.$message.success('删除成功!')
          this.closeEditGroupForm()
          this.search()
        })
        .catch((error) => {
          if (error.response) {
            this.$message.error(`删除失败! ${error.response.data.message}`)
          } else {
            this.$message.error(`删除失败! ${error.message}`)
          }
        })
    },
    leaveGroup (selection) {
      let _id = selection.id
      if (Array.isArray(selection)) {
        _id = selection.map(row => row.id).join(',')
      }
      this.$http.put(this.$apiUrl('systemGroup012', [_id]))
        .then(response => {
          this.$message.success('操作成功!')
        })
        .catch((error) => {
          if (error.response) {
            this.$message.error(`操作失败! ${error.response.data.message}`)
          } else {
            this.$message.error(`操作失败! ${error.message}`)
          }
        })
    },
    toFreezeGroup (selection) {
      if (!selection.id && selection.length === 0) {
        this.$message.warning('请选择要冻结的用户组')
      } else {
        this.$confirm('确认冻结用户组, 是否继续?', '冻结用户组', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.freezeGroup(selection)
        })
      }
    },
    toEditGroup () {
      if (!this.currentRow) {
        this.$message.warning('请选择要编辑的用户组')
      } else {
        this.closeEditGroupForm()
        this.$nextTick(() => {
          Object.keys(this.groupForm).forEach(k => {
            this.groupForm[k] = this.currentRow[k]
          })
          this.showEditGroupForm()
        })
      }
      this.clearValidate()
    },
    showCreateGroupForm () {
      this.createGroupFormShow = true
      this.editGroupFormShow = false
    },
    closeCreateGroupForm () {
      this.createGroupFormShow = false
    },
    showEditGroupForm () {
      this.editGroupFormShow = true
      this.createGroupFormShow = false
    },
    closeEditGroupForm () {
      this.editGroupFormShow = false
    },
    // 清空form表单
    resetForm () {
      this.$resetToEmpty(this.groupForm)
      this.saving = false
    },
    clearValidate () {
      // 移除整个表单的校验结果
      this.$nextTick(() => {
        this.$refs.groupForm && this.$refs.groupForm.clearValidate()
      })
      this.$nextTick(() => {
        this.$refs.batchGroupForm && this.$refs.batchGroupForm.clearValidate()
      })
    },
    handleSelectionChange (val) {
      this.nowSelectChangeRows = val
    },
    tableCurrentChange (currentRow, oldCurrentRow) {
      this.currentRow = currentRow
      if (this.currentRow) this.toEditGroup()
    },
    renderHeader (h, { column }) {
      return h('span', { domProps: { innerHTML: column.label } })
    },
    parseGroupFlag (flag) {
      if (flag === '1') {
        return '受限'
      } else if (flag === '2') {
        return '冻结'
      } else if (flag === '4') {
        return '删除'
      } else {
        return '可用'
      }
    }
  }
}
</script>
<style lang="scss" scoped>
  @import '../../style/mixin';
  .fixed-header {
    height: 50px;
    line-height: 50px;
    width: 100%;
    top: -10px;
    right: 0;
    z-index: 99;
    position: absolute;
    background: $white-color;
    box-shadow: 2px 1px 5px rgba(0,0,0,0.15);
  }
  .row-button {
    margin-left: 15px;
  }
  .more {
    cursor: pointer;
  }
  .el-link {
    vertical-align: top !important;
  }
  .custom-password-wrapper {
    background: white;
    margin-top: 10px;
    height: 44px;
    align-items: center;
    display: flex;
    padding: 0px 10px;
    border: 1px solid #E4E4E4;
    justify-content: flex-start;
    span:first-child {
      color: #999999;
      margin-right: 20px;
    }
    .el-input {
      width: auto;
    }
  }
  .add-group-wrapper {
    background: white;
    margin-top: 10px;
    padding: 10px;
    border: 1px solid #E4E4E4;
  }
  .table-height-auto.el-table {
    height: auto !important;
  }
</style>
