<script lang="ts">
export default {
  inheritAttrs: false
}
</script>

<script setup lang="ts">
import router from '@/router'
import { ElMessage, ElMessageBox, type DialogProps } from 'element-plus'
import type { AdvancedForm, BasicForm, ICRUD } from '@/types/form'
import type { VXEComponent, VxeToolbarProps, VxeToolbarEventProps } from 'vxe-table'

interface CustomTable {
  showOperate?: boolean
  showEdit?: boolean
  showDelete?: boolean
  operateWidth?: number
}

interface Props {
  crud: ICRUD
  pageSize?: number
  selection?: boolean
  formConfig: BasicForm | AdvancedForm
  dialogConfig?: DialogProps
  tableConfig?: CustomTable
  toolbarConfig?: VXEComponent<VxeToolbarProps, VxeToolbarEventProps>
  showToolbar?: boolean
  height?: string
}

const props = withDefaults(defineProps<Props>(), {
  pageSize: 10,
  selection: true,
  showToolbar: true
})

const emits = defineEmits(['click-create', 'click-edit'])

const slots = useSlots()

// ============== 查询部分开始 ===============
const query = ref<any>({})
const searchList = ref<any>([])
watch(
  () => props.formConfig.formItems,
  val => {
    val.forEach((item: any) => {
      if (item.group) {
        searchList.value = searchList.value.concat(item.group.filter((item: any) => item.search))
      } else {
        item.search && searchList.value.push(item)
      }
    })
  },
  { immediate: true }
)

const handleQuery = () => {
  curPage.value = 1
  getTableData()
}
const handleReset = () => {
  query.value = {}
  handleQuery()
}
// ============== 查询部分结束 ===============

// ============== 表格部分开始 ===============
const tableData = ref([])
const total = ref(0)
const curPage = ref(1)
const loading = ref(false)
const tableConfig = ref<CustomTable>({
  showOperate: true,
  showEdit: true,
  showDelete: true,
  operateWidth: 140,
  ...props.tableConfig
})

const xTable = ref<any>()
const xToolbar = ref<any>()

nextTick(() => {
  // 将表格和工具栏进行关联
  const $table = xTable.value
  const $toolbar = xToolbar.value
  $toolbar && $table.connect($toolbar)
})

const getTableData = () => {
  loading.value = true
  props.crud
    ?.getList({
      ...query.value,
      pageSize: props.pageSize,
      pageNo: curPage.value
    })
    .then((res: any) => {
      tableData.value = res.list || res.rows
      total.value = res.total
    })
    .finally(() => {
      loading.value = false
    })
}

watch(
  curPage,
  () => {
    getTableData()
  },
  {
    immediate: true
  }
)

const refresh = () => {
  curPage.value = 1
  getTableData()
}

const multipleSelection = ref<any[]>([])
const handleSelectionChange = () => {
  multipleSelection.value = xTable.value.getCheckboxRecords()
}
// ============== 表格部分结束 ===============

// ============== crud部分开始 ===============
const formRoute = ref<any>(props.formConfig.route)
const handleCreate = () => {
  emits('click-create')
  if (formRoute.value) {
    router.push(formRoute.value)
  } else {
    formData.value = {}
    dialogVisible.value = true
  }
}
const handleUpdate = (row: any) => {
  emits('click-edit', row)
  if (formRoute.value) {
    router.push(formRoute.value)
  } else {
    if (props.crud?.getRecord) {
      props.crud.getRecord({ id: row.id }).then((res: any) => {
        formData.value = res.data
      })
    } else {
      formData.value = { ...row }
    }
    dialogVisible.value = true
  }
}
const handleDelete = (id: string | number) => {
  ElMessageBox.confirm('您确定要删除该项吗', '提示', {
    type: 'warning'
  }).then(async () => {
    await props.crud?.delete({ id })
    getTableData()
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
  })
}
const handleBatchDelete = () => {
  ElMessageBox.confirm('您确定要删除吗', '提示', {
    type: 'warning'
  }).then(async () => {
    if (props.crud.deleteBatch) {
      await props.crud?.deleteBatch({
        ids: multipleSelection.value.map(item => item.id).join(',')
      })
      getTableData()
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
    } else {
      ElMessage({
        type: 'error',
        message: '未提供deleteBatch方法'
      })
    }
  })
}
// ============== crud部分结束 ===============

// ============== 表单部分开始 ===============
const formData = ref<any>({})
const dialogVisible = ref(false)
const handleFormSuccess = () => {
  getTableData()
}
// ============== 表单部分结束 ===============

defineExpose({
  handleCreate,
  handleDelete,
  handleUpdate,
  refresh
})
</script>

<template>
  <div class="flex flex-col" :style="{ height: height || 'calc(100vh - 101px - var(--main-padding) * 2)' }">
    <el-card class="mb-4" shadow="never" v-if="searchList.length || slots.query">
      <el-form :inline="true">
        <el-form-item :label="item.label" v-for="(item, index) in searchList" :key="index">
          <form-comp :item="item" v-model="query[item.name]"></form-comp>
        </el-form-item>
        <slot name="query" :query="query"></slot>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
          <el-button icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="h-full flex-grow-1" :body-style="{ height: '100%' }" shadow="never">
      <div class="flex flex-col h-full">
        <slot name="header"></slot>
        <vxe-toolbar ref="xToolbar" v-bind="toolbarConfig" v-if="showToolbar">
          <template #buttons>
            <el-button type="primary" icon="Plus" @click="handleCreate">新增</el-button>
            <el-button
              type="danger"
              icon="Delete"
              @click="handleBatchDelete"
              :disabled="!multipleSelection.length"
              v-if="selection"
            >
              删除
            </el-button>
            <slot name="toolbar" :selection="multipleSelection"></slot>
          </template>
        </vxe-toolbar>
        <div class="h-full flex-grow">
          <vxe-table
            ref="xTable"
            id="xProTable"
            size="medium"
            height="100%"
            :data="tableData"
            :row-config="{ isHover: true }"
            v-loading="loading"
            v-bind="$attrs"
            @checkbox-change="handleSelectionChange"
            @checkbox-all="handleSelectionChange"
          >
            <vxe-column type="checkbox" width="50" v-if="selection"></vxe-column>
            <slot></slot>
            <vxe-column fixed="right" title="操作" :width="tableConfig.operateWidth" v-if="tableConfig.showOperate">
              <template #default="{ row }">
                <slot name="operateBefore" :row="row"></slot>
                <el-button type="primary" size="small" @click="handleUpdate(row)" v-if="tableConfig.showEdit">
                  编辑
                </el-button>
                <el-button type="danger" size="small" @click="handleDelete(row.id)" v-if="tableConfig.showDelete">
                  删除
                </el-button>
                <slot name="operateAfter" :row="row"></slot>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
        <div class="flex justify-end shrink-0">
          <el-pagination
            background
            layout="prev, pager, next, jumper, total"
            v-model:current-page="curPage"
            :page-size="pageSize"
            :total="total"
            class="mt-16px"
          />
        </div>
      </div>
    </el-card>

    <dialog-form
      v-model="dialogVisible"
      :dialogConfig="dialogConfig"
      :formConfig="formConfig"
      :formData="formData"
      :create="crud.create"
      :update="crud.update"
      @success="handleFormSuccess"
      v-if="dialogVisible"
    />
  </div>
</template>

<style scoped>
.vxe-toolbar {
  padding-top: 0;
}
</style>
