<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import {
  getSysRoleListApi,
  saveSysRoleApi,
  delSysRoleListApi,
  delSysRoleApi,
  querySysRoleApi,
  exportExcelApi,
  importExcelApiUrl
} from '@/api/system/SysRole'
import { TableData } from '@/api/dataManage/dataSetManage/types'
import { Upload } from '@/components/Upload'
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 Detail from './components/Detail.vue'
import { Dialog } from '@/components/Dialog'

defineOptions({
  name: 'DataSetManage'
})

const { t } = useI18n()

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

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getSysRoleListApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.body.list,
      total: res.body.total
    }
  },
  fetchDelApi: async () => {
    const res = await delSysRoleListApi(unref(ids))
    return res?.head?.code === '0' ? true : false
  }
})

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: 'id',
    label: '主键'
  },
  {
    field: 'organId',
    label: '机构号'
  },
  {
    field: 'name',
    label: '角色名称'
  },
  {
    field: 'dataScope',
    label: '权限范围'
  },
  {
    field: 'createBy',
    label: '创建人'
  },
  {
    field: 'createDate',
    label: '创建时间'
  },
  {
    field: 'updateBy',
    label: '最近修改人'
  },
  {
    field: 'updateDate',
    label: '最近修改时间'
  },
  {
    field: 'delFlag',
    label: '逻辑删除标记'
  },
  {
    field: 'remarks',
    label: '描述'
  },
  {
    field: 'action',
    label: t('tableDemo.action'),
    width: 160,
    slots: {
      default: (data: any) => {
        return (
          <>
            <ElLink type="primary" underline={false} onClick={() => action(data.row, 'edit')}>
              {t('tableDemo.edit')}
            </ElLink>
            <ElLink type="primary" underline={false} onClick={() => action(data.row, 'detail')}>
              {t('tableDemo.detail')}
            </ElLink>
            <ElPopconfirm
              title={t('tableDemo.delTableMsg')}
              width={200}
              v-slots={{
                reference: () => {
                  return (
                    <>
                      <ElLink type="primary" underline={false}>
                        {t('tableDemo.del')}
                      </ElLink>
                    </>
                  )
                }
              }}
              onConfirm={() => delData(data.row)}
            ></ElPopconfirm>
          </>
        )
      }
    }
  }
])

/** 查询 */
const searchSchema = reactive<FormSchema[]>([
  {
    field: 'name',
    label: '角色名称',
    component: 'Input'
  },
  {
    field: 'delFlag',
    label: '逻辑删除标记',
    component: 'Select',
    componentProps: {
      options: [
        {
          label: '正常',
          value: '0'
        },
        {
          label: '删除',
          value: '1'
        }
      ]
    }
  }
])

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 querySysRoleApi(row.id)
    .catch(() => {})
    .finally(() => {
      detailLoading.close()
    })
  detailLoading.close()
  if (res) {
    const data = res.body.result
    dialogTitle.value = t(type === 'edit' ? 'tableDemo.edit' : 'tableDemo.detail')
    actionType.value = type
    currentRow.value = data
    dialogVisible.value = true
  }
}

/** 新增 */
const AddAction = () => {
  dialogTitle.value = t('tableDemo.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 saveSysRoleApi(formData)
      .catch(() => {})
      .finally(() => {
        saveLoading.value = false
      })
    if (res) {
      const { code, msg } = res?.head
      if (code === '0') {
        dialogVisible.value = false
        currentPage.value = 1
        getList()
      } else {
        ElMessage.error(msg || t('common.operateFail'))
      }
    }
  }
}

const delLoading = ref(false)

/** 批量删除 */
const delDataBatch = async () => {
  const elTableExpose = await getElTableExpose()
  ids.value = elTableExpose?.getSelectionRows().map((v: TableData) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

/** 删除 */
const delData = async (row: TableData) => {
  delLoading.value = true
  const res = await delSysRoleApi(row.id)
  delLoading.value = false
  if (res) {
    const { code, errMsg } = res.head
    if (code === '0') {
      ElMessage.success('删除成功!')
      getList()
    } else {
      ElMessage.error(errMsg || '删除失败!')
    }
  }
}

const disabled = ref(true)

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

/** 导出Excel */
const exportExcel = async () => {
  const data = { ...unref(searchParams) }
  await exportExcelApi(data)
}
</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('tableDemo.add') }}</ElButton>
        <Upload :url="importExcelApiUrl" :callback="getList">
          <ElButton type="primary">导入</ElButton>
        </Upload>
        <ElButton type="primary" @click="exportExcel()">导出</ElButton>
        <ElButton :loading="delLoading" type="primary" :disabled="disabled" @click="delDataBatch()">
          {{ t('tableDemo.del') }}
        </ElButton>
      </template>
    </Table>
  </ContentWrap>

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

    <Detail v-if="actionType === 'detail'" :current-row="currentRow" />

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