<template>
  <div class="layout-no-cols scroll role-info-page">
    <el-toolbar>
      <el-button @click="$router.back()" type="primary" size="medium" round class="shadow-primary">
      <i class="fa fa-chevron-left"></i> 返回上页</el-button>
      <span class="button-separator"></span>
      <el-button type="button" class="el-button el-button--default save" priv="Platform.Role.Add||Platform.Role.Edit" :loading="confirmLoading" @click="okHandler"><span><i class="fa fa-save"></i>保存</span></el-button>
    </el-toolbar>
    <div class="detail-panel edit-member-page">
      <div class="panel-header">
        <div class="title">{{isEdit ? '基本信息' : '添加新角色'}}</div>
      </div>
      <el-form :model="roleInfo" ref="roleForm" label-width="120px" label-suffix="：" v-loading="dialogLoading" class="role-add-form">
        <el-row>
          <el-col :span="12">
            <el-form-item label="角色名" prop="roleName" :verify="['NotNull']">
              <el-input v-model="roleInfo.roleName"></el-input>
              <i class="fa fa-language" title="多语言设置" @click="langBtnClickHandler('roleName',roleInfo.roleName,roleInfo.roleName_I18N)"></i>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色代码" prop="roleCode" :verify="['NotNull','Regex=^[a-zA-Z0-9_]{1,16}$|请用1-16位的英文字母、数字、下划线']">
              <el-input v-model="roleInfo.roleCode" :disabled="isEdit"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属机构" prop="branchInnerCode" :verify="['NotNull']">
              <tree-select :value.sync="roleInfo.branchInnerCode" :items="branchTree" :style="{'width':'auto'}" :itemsOptions="treeItemsOptions" :disabled="isEdit" placeholder="请选择">
              </tree-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注">
              <el-input v-model="roleInfo.memo"></el-input>
              <i class="fa fa-language" title="多语言设置" @click="langBtnClickHandler('memo',roleInfo.memo,roleInfo.memo_I18N)"></i>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="right-detail-toolbar" v-if="isEdit">
      <el-toolbar>
        <el-button @click="addUsersToRoleClickHandler" priv="Platform.Role.AddUser"><i class="fa fa-plus"></i> 添加用户到角色</el-button>
      </el-toolbar>
      <div class="panel-card padding0 role-users">
        <el-table :data="userData" style="margin:0;">
          <el-table-column type="index" width="80" label="序号" align="center"></el-table-column>
          <el-table-column prop="userName" label="用户名" width="150"></el-table-column>
          <el-table-column prop="realName" label="真实姓名" width="150"></el-table-column>
          <el-table-column label="所属角色">
            <template slot-scope="scope">
              <span v-for="(role, index) in scope.row.roles" :key="role.roleCode">
                {{index==0?'':', '}}{{role.name}}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="right" width="100">
            <template slot-scope="scope">
              <el-button @click.stop="deleteUsersToRoleClickHandler(scope.row)" priv="Platform.Role.RemoveUser"
                type="text" title="从角色中删除用户">
                <i class="fa fa-minus f18" style="color:#28B06E"></i></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <el-tabs class="tabs-wrap" v-model="activeName" @tab-click="onRoleTabsClick">
        <el-tab-pane :label="type.name" :name="type.code" v-for="type in rolePermissionTypes" :key="type.code">
          <component v-if="activeName===type.code" :is="type.code" :id="tmpRoleCode" type="R"></component>
        </el-tab-pane>
      </el-tabs>
    </div>

    <role-user-select
      :role-code="tmpRoleCode"
      :show.sync="isShowModal"
      @callback="afterAddUserToRole">
    </role-user-select>
    <!-- 多语言编辑器 -->
    <lang-edit-dlg
      :show.sync="langDialog.isShowModal"
      :ID="langDialog.ID"
      :targetValue="langDialog.targetValue"
      :languages="langDialog.languages"
      @callback="getI18nBack">
    </lang-edit-dlg>
  </div>
</template>
<script>
import util from '@src/common/util.js'
import RoleUserSelectDialog from './RoleUserSelectDialog.vue'
import MenuPermission from './MenuPermission.vue'
import SitePermission from './SitePermission.vue'
import APIPermission from './APIPermission.vue'
import CatalogPermission from './CatalogPermission.vue'
import DocPermission from './DocPermission.vue'
import ModulesPermission from './ModulesPermission.vue'
import BlockPermission from './BlockPermission.vue'
import TreeSelect from '@src/components/TreeSelect.vue'
import LangEditDialog from '@src/pages/platform/components/LangEditDialog.vue'
export default {
  components: {
    'tree-select': TreeSelect,
    'lang-edit-dlg': LangEditDialog,
    'role-user-select': RoleUserSelectDialog,
    menuPermission: MenuPermission,
    sitePermission: SitePermission,
    apiPermission: APIPermission,
    catalogPermission: CatalogPermission,
    modulesPermission: ModulesPermission,
    docPermission: DocPermission,
    blockPermission: BlockPermission
  },
  props: {
    roleCode: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      tmpRoleCode: '',
      isEdit: false,
      langDialog: {
        isShowModal: false,
        ID: '',
        languages: '',
        targetValue: ''
      },
      confirmLoading: false,
      dialogLoading: false,
      userData: [], // 用户列表
      isShowModal: false,
      rolePermissionTypes: [], // 权限类型
      activeName: '', // 当前分页名称
      roleInfo: {},
      branchTree: [], // 机构
      treeItemsOptions: {
        children: 'children',
        label: 'name',
        key: 'branchInnerCode'
      }
    }
  },
  async created() {
    this.isEdit = this.roleCode !== 'new'
    this.tmpRoleCode = this.isEdit ? this.roleCode : ''
    await this.loadBranch()
    if (this.isEdit) {
      this.initRoleInfo()
      this.loadRoleUsers()
      this.loadRolePermissionTypes()
    }
  },
  methods: {
    getI18nBack(data) {
      if (data.ID === 'roleName') {
        this.roleInfo.roleName = data.val
        this.roleInfo.roleName_I18N = data.data
      }
      if (data.ID === 'memo') {
        this.roleInfo.memo = data.val
        this.roleInfo.memo_I18N = data.data
      }
    },
    langBtnClickHandler(ID, value, languages) {
      this.langDialog.isShowModal = true
      this.langDialog.ID = ID
      this.langDialog.languages = languages
      this.langDialog.targetValue = value
    },
    async okHandler() {
      this.confirmLoading = true
      try {
        await util.validateForm(this.$refs['roleForm'])
        let res
        if (this.isEdit) {
          res = await axios.put(`/ui/roles/${this.tmpRoleCode}`, this.roleInfo)
          util.showResponseMessage(res.data)
        } else {
          res = await axios.post('/ui/roles', this.roleInfo)
          util.showResponseMessage(res.data)
          if (res.data.status === 1) {
            this.tmpRoleCode = this.roleInfo.roleCode
            this.isEdit = true
            this.loadRoleUsers()
            this.loadRolePermissionTypes()
          }
        }
        this.confirmLoading = false
      } catch (e) {
        util.showErrorMessageBox(e)
        this.confirmLoading = false
      }
    },
    async loadBranch() {
      let res = await axios.get('/ui/branches')
      this.branchTree = res.data.status === 1 ? res.data.data : []
    },
    async initRoleInfo() {
      this.dialogLoading = true
      let res
      try {
        res = await axios.get(`/ui/roles/${this.tmpRoleCode}`)
      } catch (e) {
        this.dialogLoading = false
        return
      }
      this.dialogLoading = false
      if (res.data.status === 1) {
        this.roleInfo = res.data.data
      }
    },
    async loadRoleUsers() {
      let res = await axios.get(`/ui/roles/${this.tmpRoleCode}/users`)
      this.userData = res.data.status === 1 ? res.data.data : []
    },
    afterAddUserToRole() {
      this.loadRoleUsers()
    },
    addUsersToRoleClickHandler() {
      this.isShowModal = true
    },
    async deleteUsersToRoleClickHandler(row) {
      if (!row || !row.userName) {
        return
      }
      try {
        await this.$confirm('确定删除吗？删除后无法恢复。是否继续删除？', '删除确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        let res = await axios.delete(`/ui/roles/${this.tmpRoleCode}/users`, {params: {usernames: row.userName}})
        util.showResponseMessage(res.data)
        if (res.data.status === 1) {
          this.userData = this.userData.filter(val => val.userName !== row.userName)
        }
      } catch (e) {

      }
    },
    async loadRolePermissionTypes() {
      let res = await axios.get(`/ui/permissions/id/none/type/none/types`)
      this.rolePermissionTypes = res.data.status === 1 ? res.data.data : []
      this.activeName = res.data.status === 1 && res.data.data.length ? res.data.data[0].code : ''
    },
    onRoleTabsClick(tab, event) {
      this.activeName = tab.name
    }
  }
}
</script>
<style scope>
.role-info-page .role-info {
  margin-top: 30px;
}
.role-info-page .role-info .info-content {
  padding: 20px;
}
.role-info-page .role-info .info-title{
  padding: 20px;
  font-weight:600;
}
.role-info-page .role-info .divider{
  height:2px;
  border-bottom: 1px solid #eee;
}
</style>
<style>
.role-add-form .el-form-item .el-input {
  width: 260px;
  margin-right: 5px;
}
/* .edit-member-page, .role-users {margin: 0;} */
</style>
