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

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

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

interface Props {
  crud: ICRUD
  pageSize?: number
  selection?: boolean
  formConfig: BasicForm
  dialogConfig?: Partial<DialogProps>
  drawerConfig?: Partial<DrawerProps>
  tableConfig?: CustomTable
  toolbarConfig?: VxeToolbarProps
  showToolbar?: boolean
  height?: string
  formMode?: 'dialog' | 'drawer'
  beforeCreate?: Function
}

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

const emits = defineEmits(['click-create', 'click-edit', 'click-view', 'click-reset', 'checkbox-change'])

const slots = useSlots()

// ============== 查询部分开始 ===============
const query = ref<any>({})
const defaultQuery = ref<any>({})
const searchList = ref<any>([])
// 构造搜索列表
const buildSearchList = (item: BasicFormItem) => {
  if (item.search) {
    searchList.value.push(Object.assign({}, item, { props: { ...item.props, disabled: false } }))
    if (item.value) {
      query.value[item.name] = item.value
      defaultQuery.value[item.name] = item.value
    }
  }
  item.children && item.children.forEach(buildSearchList)
}
watch(
  () => props.formConfig.formItems,
  val => {
    searchList.value = []
    val.forEach((item: BasicFormItem) => {
      buildSearchList(item)
    })
  },
  { immediate: true }
)

const handleQuery = () => {
  curPage.value = 1
  getTableData()
}
const handleReset = () => {
  query.value = { ...defaultQuery.value }
  emits('click-reset', query.value)
  handleQuery()
}
// ============== 查询部分结束 ===============

// ============== 表格部分开始 ===============
const tableData = ref([])
const total = ref(0)
const curPage = ref(1)
const loading = ref(false)
const tableConfig = computed<CustomTable>(() => ({
  showOperate: true,
  showView: false,
  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 || res.infos
      total.value = res.total || res.totalCount
    })
    .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()
  emits('checkbox-change', multipleSelection.value)
}
// ============== 表格部分结束 ===============

// ============== crud部分开始 ===============
const formRoute = ref<any>(props.formConfig.route)

const doCreate = () => {
  emits('click-create')
  if (formRoute.value) {
    router.push(formRoute.value)
  } else {
    formData.value = {}
    props.formConfig.disabled = false
    formVisible.value = true
  }
}
const handleCreate = async () => {
  if (!props.beforeCreate) {
    return doCreate()
  }

  let result = true
  try {
    const beforeUploadPromise = props.beforeCreate(formData.value)
    result = await beforeUploadPromise
  } catch {
    result = false
  }

  if (result === false) {
    return
  }
  doCreate()
}

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 }
    }
    props.formConfig.disabled = false
    formVisible.value = true
  }
}
const handleView = (row: any) => {
  emits('click-view', 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 }
    }
    props.formConfig.disabled = true
    formVisible.value = true
  }
}
const handleDelete = (id: string | number) => {
  ElMessageBox.confirm('您确定要删除该项吗', '提示', {
    type: 'warning'
  }).then(async () => {
    const data = await props.crud?.delete({ id })
    if (data.success || data.code === 200) {
      getTableData()
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
    } else {
      ElMessage.error(data.msg)
    }
  })
}
const handleBatchDelete = () => {
  ElMessageBox.confirm('您确定要删除吗', '提示', {
    type: 'warning'
  }).then(async () => {
    if (props.crud.deleteBatch) {
      const data = await props.crud?.deleteBatch({
        ids: multipleSelection.value.map(item => item.id).join(',')
      })
      if (data.success || data.code === 200) {
        getTableData()
        ElMessage({
          type: 'success',
          message: '删除成功'
        })
      } else {
        ElMessage.error(data.msg)
      }
    } else {
      ElMessage({
        type: 'error',
        message: '未提供deleteBatch方法'
      })
    }
  })
}
// ============== crud部分结束 ===============

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

// 构造表单插槽
const formSlots = ref<FormSlot[]>([])
buildFormSlots(props.formConfig.formItems, formSlots.value)
// ============== 表单部分结束 ===============

defineExpose({
  handleCreate,
  handleDelete,
  handleUpdate,
  handleView,
  handleQuery,
  handleReset,
  refresh,
  formData,
  query,
  table: xTable
})
</script>

<template>
  <div class="flex flex-col" style="max-height: 100vh" :style="{ height: height || '100%' }">
    <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]">
            <template #[slot.alias] v-for="slot in item.slots" :key="slot.alias">
              <slot :name="slot.alias"></slot>
            </template>
          </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="success" size="small" @click="handleView(row)" v-if="tableConfig.showView">
                  查看
                </el-button>
                <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>

    <template v-if="formMode === 'dialog'">
      <dialog-form
        v-model="formVisible"
        v-if="formVisible"
        :dialogConfig="dialogConfig"
        :formConfig="formConfig"
        :formData="formData"
        :formSlots="formSlots"
        :create="crud.create"
        :update="crud.update"
        @success="handleFormSuccess"
      >
        <template #[slot.alias]="slotProps" v-for="slot in formSlots" :key="slot.alias">
          <slot :name="slot.alias" v-bind="slotProps"></slot>
        </template>
      </dialog-form>
    </template>
    <template v-else>
      <drawer-form
        v-model="formVisible"
        v-if="formVisible"
        :drawerConfig="drawerConfig"
        :formConfig="formConfig"
        :formData="formData"
        :formSlots="formSlots"
        :create="crud.create"
        :update="crud.update"
        @success="handleFormSuccess"
      >
        <template #[slot.alias]="slotProps" v-for="slot in formSlots" :key="slot.alias">
          <slot :name="slot.alias" v-bind="slotProps"></slot>
        </template>
      </drawer-form>
    </template>
  </div>
</template>

<style scoped>
.vxe-toolbar {
  padding-top: 0;
}
:deep(.el-card) {
  --el-card-padding: 16px;
  border: none !important;
}
</style>
