<template>
  <div class="app-container">
    <el-card>
      <el-row>
        <el-form
          ref="searchForm"
          :model="queryParams"
          inline
          :label-width="'100px'"
        >
          <el-form-item
            v-if="superAdmin && enableTenant===true"
            :label="$t('ec.user.tenant')"
            prop="tenantId"
          >
            <ec-tenant v-model="queryParams.tenantId" />
          </el-form-item>
          <el-form-item
            v-if="superAdmin"
            :label="$t('ec.app.app')"
            prop="appId"
          >
            <ec-register-app
              v-model="queryParams.appId"
              default-first
              :tenant-id="queryParams.tenantId"
              :clearable="false"
              @hasInit="init"
              @change="init"
            />
          </el-form-item>
          <el-form-item
            v-if="enableRoleDept"
            :label="$t('ec.user.dept')"
            prop="deptId"
          >
            <ec-dept-select
              :data="{ appId: queryParams.appId }"
              v-model="queryParams.deptId"
              check-strictly
            />
          </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="20">
        <el-col :span="12">
          <el-alert
            :title="$t('ec.role.selectAlert')"
            type="warning"
            :closable="false"
            show-icon
          />
          <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 @click="refresh">{{ $t('ec.table.refresh') }}</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>
            </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:remark="{ row }">
              <el-tooltip placement="bottom">
                <div
                  slot="content"
                  style="font-size: 14px"
                >{{ row.remark }}<br><br>{{ row.remarkInfo }}</div>
                <span>{{ row.remark }}</span>
              </el-tooltip>
            </template>

            <template v-slot:status_operation="{ row }">
              <el-switch
                v-model="row.status"
                active-color="#13ce66"
                active-value="1"
                inactive-value="0"
                :disabled="!checkPermission(['role:edit'])"
                @change="updateStatus(row)"
              />
            </template>

            <template v-slot:role_operation="{ row }">
              <el-button
                v-permission="['role:user']"
                type="text"
                @click.stop="roleUser(row)"
              >{{ $t('ec.role.user') }}</el-button>
              <el-button
                v-permission="['role:edit']"
                type="text"
                @click.stop="edit(row)"
              >{{ $t('ec.table.edit') }}</el-button>
              <el-dropdown
                trigger="click"
                style="padding-left:10px;padding-right:10px;"
                @command="command => dropDownCmd(command, row)"
              >
                <el-button
                  type="text"
                  icon="el-icon-arrow-down"
                  size="mini"
                />
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="view">{{ $t('ec.table.view') }}</el-dropdown-item>
                  <el-dropdown-item
                    v-permission="['role:delete']"
                    command="delete"
                  >{{ $t('ec.table.delete') }}</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </vxe-grid>
        </el-col>

        <el-col :span="12">
          <el-tabs>
            <el-tab-pane :label="$t('ec.role.rsrcAuth')">
              <rsrc-auth-tab
                ref="rsrcAuthTab"
                :role-id="selectedRole.id"
              />
            </el-tab-pane>
            <el-tab-pane
              :label="$t('ec.role.dataRuleAuth')"
              v-if="getRolePageOptionsSwitch('showDataRuleAuthTab')"
            >
              <data-rule-auth-tab
                ref="dataruleAuthTab"
                :role-id="selectedRole.id"
              />
            </el-tab-pane>
            <el-tab-pane
              v-if="superAdmin && getRolePageOptionsSwitch('showOrgAuthTab')"
              :label="$t('ec.role.orgAuth')"
            >
              <org-auth-tab
                ref="orgAuthTab"
                :role-id="selectedRole.id"
              />
            </el-tab-pane>
            <el-tab-pane
              :label="$t('ec.role.deptAuth')"
              v-if="getRolePageOptionsSwitch('showDeptAuthTab')"
            >
              <dept-auth-tab
                :filterBol="true"
                ref="deptAuthTab"
                :role-id="selectedRole.id"
              />
            </el-tab-pane>
          </el-tabs>
        </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"
    />

    <copy-modal ref="copyModal" />

    <role-user-modal ref="roleUserModal" />
  </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 RsrcAuthTab from './components/rsrcAuthTab'
import DataRuleAuthTab from './components/dataRuleAuthTab'
import OrgAuthTab from './components/orgAuthTab'
import DeptAuthTab from './components/deptAuthTab'
import RoleUserModal from './components/roleUserModal'
import CopyModal from 'ecip-web/views/vue/components/copyModal'
import { download } from 'ecip-web/utils'
import config from '@/settings'
const enableTenant =
  window._CONFIG['enableTenant'] === undefined
    ? true
    : window._CONFIG['enableTenant']
const enableRoleDept =
  window._CONFIG['enableRoleDept'] === undefined
    ? false
    : window._CONFIG['enableRoleDept']
const rolePageOptions =
  window._CONFIG['rolePageOptions'] === undefined
    ? {}
    : window._CONFIG['rolePageOptions']

export default {
  name: 'VueRoleSysrRoleView',
  components: {
    Detail,
    RsrcAuthTab,
    DataRuleAuthTab,
    DeptAuthTab,
    OrgAuthTab,
    RoleUserModal,
    CopyModal
  },
  mixins: [...mixin],
  data() {
    return {
      enableTenant,
      enableRoleDept,
      rolePageOptions,
      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: 'checkbox', width: 40, fixed: 'left', align: 'center', visible: true },
        {
          type: 'radio',
          width: 40,
          fixed: 'left',
          align: 'center',
          slots: { header: 'role_header' }
        },
        {
          title: 'ec.role.code',
          field: 'code',
          minWidth: 100,
          showOverflow: true
        },
        {
          title: 'ec.role.name',
          field: 'roleName',
          minWidth: 100,
          showOverflow: true
        },
        {
          title: 'ec.user.dept',
          field: 'deptName',
          minWidth: 100,
          showOverflow: true,
          visible: enableRoleDept
        },
        {
          title: 'ec.table.status',
          field: 'status',
          width: 80,
          slots: { default: 'status_operation' }
        },
        {
          title: 'ec.role.remarks',
          field: 'remark',
          minWidth: 120,
          showOverflow: 'ellipsis',
          slots: { default: 'remark' }
        },
        {
          title: 'ec.table.actions',
          minWidth: 120,
          fixed: 'right',
          align: 'center',
          slots: { default: 'role_operation' }
        }
      ],
      roleData: [], // 角色分页查询结果
      queryParams: {
        appId: config.appId,
        deptId: null,
        tenantId: null,
        code: '',
        roleName: ''
      },
      selectedRole: {},
      roleUserVisible: false
    }
  },
  created() {
    if (!this.superAdmin) {
      this.init()
    }
  },
  methods: {
    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()
      this.$refs.rsrcAuthTab.init(
        this.queryParams.appId,
        this.queryParams.tenantId
      )
      if (this.getRolePageOptionsSwitch('showDataRuleAuthTab')) {
        this.$refs.dataruleAuthTab.init(
          this.queryParams.appId,
          this.queryParams.tenantId
        )
      }
      if (this.superAdmin && this.getRolePageOptionsSwitch('showOrgAuthTab')) {
        this.$refs.orgAuthTab.init(this.queryParams.tenantId)
      }
      if (this.getRolePageOptionsSwitch('showDeptAuthTab')) {
        this.$refs.deptAuthTab.init(
          this.queryParams.appId,
          this.queryParams.tenantId
        )
      }
    },
    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.$refs.roleEditDialog.init(
        'add',
        this.queryParams.tenantId,
        this.queryParams.appId
      )
    },
    edit(row) {
      this.$refs.roleEditDialog.init(
        'edit',
        this.queryParams.tenantId,
        this.queryParams.appId,
        row
      )
    },
    roleUser(row) {
      this.$refs.roleUserModal.init(this.queryParams.appId, row)
    },
    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()
    },
    getRolePageOptionsSwitch(option) {
      if (option === 'showOrgAuthTab') {
        return rolePageOptions.showOrgAuthTab === undefined
          ? enableTenant
          : rolePageOptions.showOrgAuthTab
      } else if (option === 'showDeptAuthTab') {
        return rolePageOptions.showDeptAuthTab === undefined
          ? !enableTenant
          : rolePageOptions.showDeptAuthTab
      } else if (option === 'showDataRuleAuthTab') {
        return rolePageOptions.showDataRuleAuthTab === undefined
          ? true
          : rolePageOptions.showDataRuleAuthTab
      }
    }
  }
}
</script>

<style scoped>
.el-alert {
  margin-top: 4px;
  margin-bottom: 10px;
}
</style>
