<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import { getRoleListApi, saveRoleApi, delRoleListApi, queryRoleApi } from '@/api/role'
import { TableData } from '@/api/role/types'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { ElButton, ElLink, ElLoading, ElPopconfirm, ElMessage } from 'element-plus'
import { Search } from '@/components/Search'
import { FormSchema } from '@/components/Form'
import { ContentWrap } from '@/components/ContentWrap'
import Write from './components/Write.vue'
import { Dialog } from '@/components/Dialog'

const { t } = useI18n()

const ids = ref<string[]>([])

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getRoleListApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.body ? res.body.list : res.data.list,
      total: res.body ? res.body.total : res.data.total
    }
  },
  fetchDelApi: async () => {
    const res = await delRoleListApi(unref(ids))
    return !!res
  }
})

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

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'selection',
    type: 'selection'
  },
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index'
  },
  {
    field: 'name',
    label: t('role.roleName')
  },
  {
    field: 'remarks',
    label: t('role.remarks')
  },
  {
    field: 'action',
    label: t('tableDemo.action'),
    width: 160,
    slots: {
      default: (data: any) => {
        return (
          <>
            <ElLink type="primary" underline={false} onClick={() => action(data.row, 'edit')}>
              {t('exampleDemo.edit')}
            </ElLink>
            <ElPopconfirm
              title={t('common.delMessage')}
              v-slots={{
                reference: () => {
                  return (
                    <>
                      <ElLink type="primary" underline={false}>
                        {t('exampleDemo.del')}
                      </ElLink>
                    </>
                  )
                }
              }}
              onConfirm={() => delAloneData(data.row)}
            ></ElPopconfirm>
          </>
        )
      }
    }
  }
])

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

const searchParams = ref({})
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 action = async (row: any, type: string) => {
  let detailLoading = ElLoading.service({
    background: 'rgba(0, 0, 0, 0.7)'
  })
  const res = await queryRoleApi(row.id)
    .catch(() => {})
    .finally(() => {
      detailLoading.close()
    })
  detailLoading.close()
  if (res) {
    const data = res.data.data.sysRole
    dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
    actionType.value = type
    currentRow.value = {
      id: data.id,
      name: data.name,
      remarks: data.remarks,
      menuIds: data.menuIds
    }
    dialogVisible.value = true
  }
}

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

const saveLoading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    const res = await saveRoleApi(formData)
      .catch(() => {})
      .finally(() => {
        saveLoading.value = false
      })
    if (res) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
    }
  }
}

const delLoading = ref(false)

const delData = async (row: TableData | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: TableData) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

const delAloneData = async (row: TableData) => {
  delLoading.value = true
  const res = await delRoleListApi([row.id])
    .catch(() => {})
    .finally(() => {
      delLoading.value = false
    })
  delLoading.value = false
  if (res) {
    const { code } = res.data
    if (code === 1) {
      ElMessage.success('操作成功!')
      getList()
    } else {
      ElMessage.error('操作失败!')
    }
  }
}

const disabled = ref(true)

const onSelectionChange = (selection: TableData[]) => {
  disabled.value = selection.length === 0
}
</script>

<template>
  <ContentWrap>
    <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />

    <Table
      :columns="tableColumns"
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      default-expand-all
      node-key="id"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total
      }"
      @selection-change="onSelectionChange"
      @register="tableRegister"
      @refresh="refresh"
    >
      <template #buttons>
        <ElButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</ElButton>
        <ElButton :loading="delLoading" type="primary" :disabled="disabled" @click="delData(null)">
          {{ t('exampleDemo.del') }}
        </ElButton>
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write v-if="actionType !== 'detail'" ref="writeRef" :current-row="currentRow" />

    <template #footer>
      <ElButton v-if="actionType !== 'detail'" type="primary" :loading="saveLoading" @click="save">
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>
