<template>
  <div>
    <n-card>
      <HeadSearch :info="search" @search="handleSearch" @reset="handleSearch" />
      <DataTable
        ref="tableRef"
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        :scroll-x="1200"
        size="large"
      >
        <template #tableTitle>
          <n-button
            v-if="permissionList.includes('system:role:create')"
            type="primary"
            @click="handleModal"
          > {{ getPermissionLabel('system:role:create') }} </n-button>
        </template>
      </DataTable>
    </n-card>
  </div>
  <!-- 新增、编辑弹窗 -->
  <RoleModal v-if="modalShow" v-model:visible="modalShow" :data="rowData" :type="modalType" @reload="handleSearch" />
  <AuthModal v-if="relateShow" v-model:visible="relateShow" :data="rowData" :type="modalType" @reload="handleSearch" />
</template>

<script>
import search from './tools/search.js'
import table from './tools/table.js'
import HeadSearch from '@/components/Search/index.vue'
import DataTable from '@/components/DataTable/index.vue'
import RoleModal from './components/RoleModal.vue'
import AuthModal from './components/AuthModal.vue'
import { getRoleList } from '@/api/system/role/index.js'
import { unref, toRefs, reactive, onUnmounted } from 'vue'
import { usePermissionStore } from '@/store/modules/permission'

export default {
  name: 'UserManage',
  components: { DataTable, HeadSearch, RoleModal, AuthModal },
  setup() {
    const permissionStore = usePermissionStore()

    const data = reactive({
      ...toRefs(table),
      search,
      permissionList: permissionStore.accessPermissionCodes

    })
    const getPermissionLabel = (code) => {
      return permissionStore.accessPermissions.find((item) => {
        return item.code === code
      })?.name || ''
    }
    const loadDataTable = async(res) => {
      const _params = {
        ...unref(data.searchParams),
        ...res
      }
      return await getRoleList(_params)
    }

    // 新增
    function handleModal() {
      data.rowData = null
      data.modalType = 'create'
      data.modalShow = true
    }

    onUnmounted(() => {
      data.searchParams = null
      data.modalShow = false
    })

    return {
      ...toRefs(data),
      loadDataTable,
      handleModal,
      getPermissionLabel
    }
  }
}
</script>
<style scoped lang='scss'>
.n-button + .n-button {
  margin-left: 10px;
}
</style>
