<script setup lang="tsx">
import { reactive, ref, toRaw, unref } from 'vue'
import {
  addRole,
  authRole,
  authUsers,
  delAuthUsers,
  getRoleList,
  updateRole,
  getAuthUsers
} from '../../../api/system-config/role'
import { useTable } from '../../../hooks/web/useTable'
import { useI18n } from '../../../hooks/web/useI18n'
import { Table, TableColumn } from '../../../components/Table'
import { Search } from '../../../components/Search'
import { FormSchema } from '../../../components/Form'
import { ContentWrap } from '../../../components/ContentWrap'
import Write from './components/Write.vue'
import Auth from './components/Auth.vue'
import { SelectUser, ISelectUser } from '../../../business-components/SelectUser'
import { Dialog } from '../../../components/Dialog'
import { BaseButton } from '../../../components/Button'
import { useRouter } from 'vue-router'
import { useBtnAuth } from '../../../hooks/web/useBtnAuth'
import { useUserStore } from '../../../store/modules/user'

const { t } = useI18n()

const router = useRouter()
const appId = useUserStore().getAppId
// const appId = ''

const btns = useBtnAuth(router.currentRoute.value?.fullPath)
const directivesArgs = { btns }

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await getRoleList({
      roleName: unref(searchParams)?.roleName,
      current: currentPage.value,
      size: pageSize.value,
      appId
    })
    return {
      list: res.data.list || [],
      total: Number(res.data.totalCount || 0)
    }
  }
})

const { dataList, loading, total, pageSize, currentPage } = tableState
const { getList } = tableMethods

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: t('userDemo.index'),
    type: 'index'
  },
  {
    field: 'roleName',
    label: t('role.roleName')
  },
  // {
  //   field: 'status',
  //   label: t('menu.status'),
  //   slots: {
  //     default: (data: any) => {
  //       return (
  //         <>
  //           <ElTag type={data.row.status === 0 ? 'danger' : 'success'}>
  //             {data.row.status === 1 ? t('userDemo.enable') : t('userDemo.disable')}
  //           </ElTag>
  //         </>
  //       )
  //     }
  //   }
  // },
  {
    field: 'roleCode',
    label: '角色编码'
  },
  // {
  //   field: 'remark',
  //   label: t('userDemo.remark')
  // },
  {
    field: 'action',
    label: t('userDemo.action'),
    width: 290,
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            <BaseButton
              v-hasPermi={['edit', directivesArgs]}
              type="primary"
              size="small"
              onClick={() => action(row, 'edit')}
            >
              {t('exampleDemo.edit')}
            </BaseButton>
            <BaseButton
              v-hasPermi={['auth', directivesArgs]}
              type="primary"
              size="small"
              onClick={() => action(row, 'auth')}
            >
              {'授权'}
            </BaseButton>
            <BaseButton
              v-hasPermi={['user', directivesArgs]}
              type="primary"
              size="small"
              onClick={() => action(row, 'users')}
            >
              {'配置人员'}
            </BaseButton>
            <BaseButton
              v-hasPermi={['del', directivesArgs]}
              onClick={() => del(row)}
              type="danger"
              size="small"
            >
              {'删除'}
            </BaseButton>
          </>
        )
      }
    }
  }
])

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'roleName',
    label: t('role.roleName'),
    component: 'Input'
  }
])

const searchParams = ref<any>({})
const setSearchParams = (data: any) => {
  searchParams.value = data
  getList()
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref()
const actionType = ref('')

const writeRef = ref<ComponentRef<typeof Write>>()
const authRef = ref<ComponentRef<any>>(null)
const usersRef = ref<ComponentRef<any>>(null)

const saveLoading = ref(false)

const selectUsers = ref<ISelectUser[]>([])

const action = async (row: any, type: string) => {
  const titleMap = {
    edit: '修改',
    auth: '授权',
    users: '配置人员'
  }
  dialogTitle.value = titleMap[type]
  actionType.value = type
  currentRow.value = row
  if (type === 'users') {
    const res = await getAuthUsers({ appRoleId: row.appRoleId })
    selectUsers.value = res?.data
  }
  dialogVisible.value = true
}

const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = undefined
  dialogVisible.value = true
  actionType.value = 'add'
}

const del = async (row) => {
  ElMessageBox.confirm('确认删除？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await delAuthUsers({ appRoleId: toRaw(row).appRoleId })
    getList()
  })
}

const save = async () => {
  const write = unref(writeRef)
  const auth = unref(authRef)
  const users = unref(usersRef)
  const formData = await write?.submit()
  const authFormData = await auth?.submit()
  const usersFormData = await users?.submit()
  if (formData || authFormData || usersFormData) {
    let res
    if (actionType.value === 'edit') {
      res = await updateRole({
        ...toRaw(currentRow.value),
        roleCode: formData?.roleCode,
        roleName: formData?.roleName,
        appId
      })
    } else if (actionType.value === 'add') {
      res = await addRole({ ...formData, appId })
    } else if (actionType.value === 'auth') {
      res = await authRole({ appRoleId: authFormData.appRoleId, funIds: authFormData.menu })
    } else if (actionType.value === 'users') {
      res = await authUsers({ ...usersFormData, appRoleId: currentRow.value.appRoleId })
    }
    saveLoading.value = false

    const { success } = res
    if (success) {
      dialogVisible.value = false
      getList()
    }
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />
    <div class="mb-10px">
      <BaseButton v-hasPermi:[directivesArgs]="'add'" type="primary" @click="AddAction"
        >{{ '新增' }}
      </BaseButton>
    </div>
    <Table
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :columns="tableColumns"
      default-expand-all
      node-key="id"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total
      }"
      @register="tableRegister"
    />
  </ContentWrap>

  <Dialog
    :width="actionType === 'users' ? '1200px' : '700px'"
    maxHeight="582px"
    v-model="dialogVisible"
    :title="dialogTitle"
    class="scrollbar-view-full"
  >
    <Write
      v-if="!['auth', 'users'].includes(actionType)"
      ref="writeRef"
      :current-row="currentRow"
    />
    <Auth ref="authRef" v-if="actionType === 'auth'" :current-row="currentRow" />
    <SelectUser ref="usersRef" v-if="actionType === 'users'" :select-users="selectUsers" />

    <template #footer>
      <BaseButton type="primary" :loading="saveLoading" @click="save">
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
