<template>
  <div class="appRole-container">
    <el-card>
      <el-row>
        <el-form ref="searchForm" :model="queryParams" inline :label-width="'80px'">
          <el-form-item v-if="enableTenant===true" :label="$t('ec.user.tenant')" prop="tenantId">
            <ec-tenant-by-pro v-model="queryParams.tenantId" :placeholder="$t('ec.user.tenant')" @getTenant="getTenant" />
          </el-form-item>
          <el-form-item v-if="superAdmin" :label="$t('ec.app.app')" prop="appId">
            <ec-register-app ref="ecRegister" v-model="queryParams.appId" clearable filterable default-first :tenant-id="queryParams.tenantId" :is-init="false" :disabled="!Boolean(queryParams.tenantId)" @change="getData('change')" />
          </el-form-item>
          <el-form-item :label="$t('ec.role.code')" prop="code">
            <el-input v-model="queryParams.code" type="text" :placeholder="$t('ec.role.code')" />
          </el-form-item>
          <el-form-item :label="$t('ec.role.name')" prop="roleName">
            <el-input v-model="queryParams.roleName" type="text" :placeholder="$t('ec.role.name')" />
          </el-form-item>
          <el-form-item class="searchItem" :label-width="'50px'">
            <el-button type="primary" @click="queryData">{{ $t('ec.table.query') }}</el-button>
            <el-button type="default" @click="handleReset">{{ $t('ec.table.reset') }}</el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="24">
          <vxe-grid
            ref="vxe"
            row-key
            show-overflow
            show-header-overflow
            max-height="1000"
            highlight-current-row
            highlight-hover-row
            border
            resizable
            sync-resize
            auto-resize
            class="vxe-table-element"
            :loading="loading"
            :start-index="(page.currentPage - 1) * page.pageSize"
            :pager-config="page"
            :columns="columns"
            :data="roleData"
            :toolbar="tableToolbar"
            @current-change="currentRowChange"
            @radio-change="radioRowChange"
            @page-change="handlePageChange"
          >
            <template v-slot:role_toolbar_btns>
              <el-button v-permission="['role:add']" type="primary" @click="add">{{ $t('ec.table.add') }}</el-button>
              <el-button v-permission="['role:copy']" type="success" @click="copyRole">{{ $t('ec.table.copy') }}</el-button>
              <el-button v-permission="['role:delete']" type="danger" :disabled="!selectedRole || JSON.stringify(selectedRole) === '{}'" @click="deleteByIds()">
                {{ $t('ec.table.delete') }}
              </el-button>
              <el-button v-permission="['role:import']" type="primary" @click="importVisible = true">{{ $t('ec.table.import') }}</el-button>
              <el-button v-permission="['role:export']" type="success" @click="exportExcel">{{ $t('ec.table.export') }}</el-button>
              <!--              <el-button @click="refresh">{{ $t('ec.table.refresh') }}</el-button>-->
            </template>

            <template v-slot:role_header>
              <vxe-tooltip :content="$t('ec.role.selectAlert')" enterable>
                <i class="el-icon-question" />
              </vxe-tooltip>
            </template>

            <template v-slot:role_member_operation="{ row }">
              <el-button v-permission="['role:user']" type="text " @click.stop="roleUser(row)">{{ $t('ec.role.checkMember') }}</el-button>
              <el-button v-permission="['role:edit']" type="text" class="text-green-color" @click.stop="edit(row)">{{ $t('ec.table.config') }}</el-button>
              <el-button v-permission="['role:delete']" type="text" class="text-red-color" @click.stop="deleteByIds(row.id)">{{ $t('ec.table.del') }}</el-button>
            </template>

            <template v-slot:role-status="{ row }">
              <span :class="{'text-blue-color':row.statusText ==='启用','text-red-color':row.statusText !=='启用'}">
                {{ row.statusText }}
              </span>
            </template>

          </vxe-grid>
        </el-col>
      </el-row>
    </el-card>

    <ec-import
      :upload-url="importUrl"
      :tpl-url="tplUrl"
      :title="$t('ec.table.import')"
      :visible="importVisible"
      :upload-params="{ isNewPk: false, strategy: 'ignore' }"
      @onSuccess="getData"
      @close="importVisible = false"
    >
      <template v-slot:extra_params="{ extraParams }">
        <el-form-item :label="$t('ec.import.isNewPk')">
          <ec-radio-group v-model="extraParams.isNewPk" :ec-data="[ {value: false, label: $t('ec.table.no')}, {value: true, label: $t('ec.table.yes') } ]" />
        </el-form-item>
        <el-form-item :label="$t('ec.import.strategy')">
          <ec-radio-group v-model="extraParams.strategy" :ec-data="[ {value: 'ignore', label: $t('ec.import.ignore')}, {value: 'overwrite', label: $t('ec.import.overwrite') } ]" />
        </el-form-item>
      </template>
    </ec-import>

    <detail ref="roleEditDialog" @refreshData="refresh" />

    <AppRoleDetail ref="appRoleDetail" @refreshData="getData" />
    <copy-modal ref="copyModal" />

    <role-user-modal ref="roleUserModal" />
    <find-member ref="findMember" />
    <role-config ref="roleConfig" />
  </div>
</template>
<script>
import mixin from 'ecip-web/utils/common-mixin'
import { getData, deleteByIds, updateStatus } from 'ecip-web/api/vue/role/sysrRoleApi'
import Detail from './components/detail'
import AppRoleDetail from './components/appRoleDetail'
import RoleUserModal from './components/roleUserModal'
import CopyModal from 'ecip-web/views/vue/components/copyModal'
import { download } from 'ecip-web/utils'
import FindMember from './components/findMember'
import RoleConfig from './components/roleConfig'
const enableTenant = window._CONFIG['enableTenant'] === undefined ? true : window._CONFIG['enableTenant']
export default {
  name: 'AppRole',
  components: { Detail, RoleUserModal, CopyModal, FindMember, RoleConfig, AppRoleDetail },
  mixins: [...mixin],
  data() {
    return {
      enableTenant,
      loading: false,
      importVisible: false,
      importUrl: `api/v1/role/sysrRole/importExcel`,
      tplUrl: `api/v1/role/sysrRole/excelTemplate`,
      exportUrl: `api/v1/role/sysrRole/exportExcel`,
      tableToolbar: {
        id: 'vue.role.sysrRoleView-toolbar',
        custom: true,
        slots: {
          buttons: 'role_toolbar_btns'
        },
        resizable: {
          storage: true
        },
        // 列操作记录
        setting: {
          storage: true
        }
      },
      page: {
        total: 0,
        currentPage: 1,
        pageSize: 10,
        align: 'left',
        pageSizes: [10, 20, 50, 100, 200, 500],
        layouts: ['Sizes', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total'],
        perfect: true
      },
      columns: [
        { type: 'radio', width: 40, fixed: 'left', align: 'center', slots: { header: 'role_header' }},
        { title: 'ec.user.tenant', field: 'tenantName', minWidth: 100, align: 'center', showOverflow: true },
        { title: 'ec.app.app', field: 'appName', minWidth: 120, align: 'center', showOverflow: true },
        { title: 'ec.role.code', field: 'code', minWidth: 100, align: 'center', showOverflow: true },
        { title: 'ec.role.name', field: 'roleName', minWidth: 120, align: 'center', showOverflow: true },
        { title: 'ec.table.status', field: 'statusText', minWidth: 40, align: 'center', showOverflow: true, slots: { default: 'role-status' }},
        { title: 'ec.role.creator', field: 'creatorName', formatter: ({ cellValue, row, column }) => { return row.creatorName + `(${row.createTime})` }, minWidth: 240, align: 'center', showOverflow: true },
        { title: 'ec.role.modifiedBy', field: 'updateName', minWidth: 100, align: 'center', showOverflow: true },
        { title: 'ec.role.remarks', field: 'remark', minWidth: 120, align: 'center', showOverflow: true },
        { title: 'ec.table.actions', field: 'action', minWidth: 200, align: 'center', fixed: 'right', slots: { default: 'role_member_operation' }}
      ],
      roleData: [], // 角色分页查询结果
      queryParams: {
        appId: null,
        tenantId: null,
        roleName: '',
        code: ''
      },
      selectedRole: {},
      roleUserVisible: false,
      tenantName: ''
    }
  },
  created() {
    if (enableTenant !== true) {
      const idx = this.columns.findIndex(item => {
        return item.field == 'tenantName'
      })
      if (typeof idx !== 'undefined') {
        this.columns.splice(idx, 1)
      }
    }
    if (!this.superAdmin) {
      this.init()
    }
  },
  methods: {
    getTenant(item) {
      this.tenantName = item.length ? item[0].label : ''
      if (!item.length) {
        this.queryParams.appId = ''
      }
    },
    async updateStatus(row) {
      try {
        this.loading = true
        const { message } = await updateStatus(row.id, { status: row.status })
        this.$notify.success(message)
        await this.getData()
      } finally {
        this.loading = false
      }
    },
    async init() { // 初始化
      await this.getData()
    },
    refresh() {
      this.init()
      this.selectedRole = {}
      this.$refs.vxe.clearCurrentRow()
    },
    radioRowChange({ row }) {
      this.selectedRole = row
      this.$refs.vxe.setCurrentRow(row)
    },
    currentRowChange({ row }) {
      this.selectedRole = row
      this.$refs.vxe.setRadioRow(row)
    },
    async getData() {
      this.selectedRole = {}

      try {
        this.loading = true
        const { data } = await getData(Object.assign({}, { size: this.page.pageSize, current: this.page.currentPage }),
          this.queryParams)
        this.roleData = data.records
        this.page.total = data.total
      } finally {
        this.loading = false
      }
    },
    add() {
      // this.drawer = true
      // this.$refs.roleEditDialog.init('add', this.queryParams.tenantId, this.queryParams.appId)
      this.$refs.appRoleDetail.init('add', this.queryParams.tenantId, this.queryParams.appId)
    },
    edit(row) {
      this.$refs.appRoleDetail.init('edit', this.queryParams.tenantId, this.queryParams.appId, row)
    },
    roleUser(row) {
      this.$refs.findMember.init(this.queryParams.appId, row, this.tenantName)
    },
    copyRole() {
      const copyUrl = 'api/v1/role/sysrRole/copyRole'
      this.$refs.copyModal.init(this.$t('ec.role.copy'), copyUrl)
    },
    // 下拉菜单点击事件
    dropDownCmd(command, row) {
      switch (command) {
        case 'view':
          this.$refs.roleEditDialog.init('view', this.queryParams.tenantId, this.queryParams.appId, row)
          break
        case 'delete':
          this.deleteByIds(row.id)
          break
      }
    },
    deleteByIds(id) {
      this.$confirm(this.$t('ec.message.delConfirm'), this.$t('ec.message.prompt'), {
        confirmButtonText: this.$t('ec.message.confirm'),
        cancelButtonText: this.$t('ec.message.cancel'),
        type: 'warning'
      }).then(async() => {
        const deleteIds = []
        if (id) {
          deleteIds.push(id)
        } else {
          // deleteIds = this.$refs.vxe.getRadioRecord().map(row => row.id)
          deleteIds.push(this.selectedRole.id)
        }
        try {
          this.loading = true
          await deleteByIds(deleteIds)
          await this.getData()
          this.$notify.success(this.$t('ec.message.delSuccess'))
        } finally {
          this.loading = false
        }
      })
    },
    handlePageChange({ currentPage, pageSize }) {
      this.page.currentPage = currentPage
      this.page.pageSize = pageSize
      this.getData()
    },
    async exportExcel() {
      this.loading = true
      await download({ url: this.exportUrl, method: 'post', data: this.queryParams })
      this.loading = false
    },
    queryData() {
      Object.assign(this.$data.page, this.$options.data().page)
      this.getData()
    },
    handleReset() {
      Object.assign(this.$data.page, this.$options.data().page)
      Object.assign(this.$data.queryParams, this.$options.data().queryParams)
      this.init()
    }
  }
}
</script>

<style scoped>
.el-alert {
  margin-top: 4px;
  margin-bottom: 10px;
}
.appRole-container{
  width: 100%;
  height: 100%;
}
</style>
